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
|
hadarl/IB_demo-master
|
IB_iteration_demo.m
|
.m
|
IB_demo-master/IB_iteration_demo.m
| 2,011 |
utf_8
|
219e60938c3aa6fbac615c0a7183f440
|
function [pXhat_X, pY_Xhat, L] = IB_iteration_demo(pXY, beta, p0Xhat_X)
yDim = size(pXY,2);
xDim = size(pXY, 1);
pX = sum(pXY,length(size(pXY)));
p0Xhat = pX'*p0Xhat_X';
%Bayes:
p0X_Xhat = (p0Xhat_X.*repmat(pX',[xDim 1])./repmat(p0Xhat',[1 xDim]))';
pY_X = (pXY./repmat(pX,[1 yDim]))';
p0Y_Xhat = pY_X * p0X_Xhat;
DKL_X_Xhat = zeros(xDim);
for i = 1:xDim
for j = 1:xDim
% DKL_X_Xhat = DKL_matrix(pY_X,pY_Xhat);
DKL_X_Xhat(i,j) = DKL2_demo(pY_X(:,i),p0Y_Xhat(:,j));
end
end
unnorm_pXhat_X = repmat(p0Xhat,[length(pX) 1]).*exp(-beta*DKL_X_Xhat);
% different rows correspond to different Xhats:
unnorm_pXhat_X = unnorm_pXhat_X';
ZX_beta = ones(length(pX)) * unnorm_pXhat_X;
% remark: we could use ones(1,length(pX)) and then replicate for the next
% operation.
pXhat_X = unnorm_pXhat_X./ZX_beta;
%Bayes:
pXhat = pX'*pXhat_X';
pX_Xhat = (pXhat_X.*repmat(pX',[xDim 1])./repmat(pXhat',[1 xDim]))';
pY_Xhat = pY_X * pX_Xhat;
[IX_Xhat, IXhat_Y] = info_curve_point_demo(pXhat_X, pY_Xhat, pXY);
L = IX_Xhat - beta*IXhat_Y;
%{
function [pXhat_X, pY_Xhat, L] = IB_iteration_demo(pXY, beta, p0Xhat_X)
pX = sum(pXY,length(size(pXY)));
yDim = size(pXY,2);
xDim = size(pXY, 1);
pXhat = pX'*p0Xhat_X';
%Bayes:
pX_Xhat = (p0Xhat_X.*repmat(pX',[xDim 1])./repmat(pXhat',[1 xDim]))';
pY_X = (pXY./repmat(pX,[1 yDim]))';
pY_Xhat = pY_X * pX_Xhat;
DKL_X_Xhat = zeros(xDim);
for i = 1:xDim
for j = 1:xDim
% DKL_X_Xhat = DKL_matrix(pY_X,pY_Xhat);
DKL_X_Xhat(i,j) = DKL2_demo(pY_X(:,i),pY_Xhat(:,j));
end
end
%repmat(pXhat,[length(pX) 1])
unnorm_pXhat_X = repmat(pXhat,[length(pX) 1]).*exp(-beta*DKL_X_Xhat);
% different rows correspond to different Xhats:
unnorm_pXhat_X = unnorm_pXhat_X';
ZX_beta = ones(length(pXhat)) * unnorm_pXhat_X;
% remark: we could use ones(1,length(pX)) and then replicate for the next
% operation.
pXhat_X = unnorm_pXhat_X./ZX_beta;
[IX_Xhat, IXhat_Y] = info_curve_point_demo(pXhat_X, pY_Xhat, pXY);
L = IX_Xhat - beta*IXhat_Y;
%}
|
github
|
bBobxx/ConjugateGradient-master
|
CongjugateGradient.m
|
.m
|
ConjugateGradient-master/CongjugateGradient.m
| 582 |
utf_8
|
f4e05309cddec5e95fa83eceacc784c7
|
%用共轭梯度法实现的求局部最小值,n为正定矩阵A的阶数,ks为误差最大值,A为正定矩阵,B为行向量。
function CongjugateGradient(n,ks,A,B)
X=randperm(n);
lambda=1;
k=1;
grad=X*A+B;
d=-1.*grad;
while(1)
grad=X*A+B ;
if dot(grad,grad)<=ks^2
fprintf('the optimal X is :')
X
fprintf('the number of iteration:')
k
break
else
if k==1
d=-1*grad;
else
d=-1*grad+((d*A*(grad.'))/(d*A*(d.')))*d;
end
end
lambda=-1*((grad*( d.'))/(d*A*(d.')));
X=X+lambda.*d;
k=k+1;
end
end
|
github
|
ChamanAgrawal/ESO208-master
|
romberg.m
|
.m
|
ESO208-master/assignment-4/romberg.m
| 1,119 |
utf_8
|
25de4dae6cf0755414bca10e88571261
|
## Copyright (C) 2017 Chaman Agrawal
##
## This program is free software; you can redistribute it and/or modify it
## under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 3 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program. If not, see <http://www.gnu.org/licenses/>.
## -*- texinfo -*-
## @deftypefn {Function File} {@var{retval} =} romberg (@var{input1}, @var{input2})
##
## @seealso{}
## @end deftypefn
## Author: Chaman Agrawal <chaman@pc>
## Created: 2017-11-09
function val = romberg (I,n,order,berg)
if(n<=1)
val = berg(1,1);
else
for i= 1:1:log2(n)
berg(1,i) = ((2^order)*I(1,i)-I(1,i+1))/(2^order-1);
end;
val= romberg(I,n/2,order+2,berg);
end;
endfunction
|
github
|
ChamanAgrawal/ESO208-master
|
f.m
|
.m
|
ESO208-master/assignment-1/problem-2/f.m
| 982 |
utf_8
|
d8df1b288b8da8d1da47c7bff07931aa
|
## Copyright (C) 2017 Chaman Agrawal
##
## This program is free software; you can redistribute it and/or modify it
## under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 3 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program. If not, see <http://www.gnu.org/licenses/>.
## -*- texinfo -*-
## @deftypefn {Function File} {@var{retval} =} f (@var{input1}, @var{input2})
##
## @seealso{}
## @end deftypefn
## Author: Chaman Agrawal <chaman@pc>
## Created: 2017-08-31
function y = f (n, coeff,x)
y=0;
for k=1:n+1
y=y+coeff(1,k)*x^(k-1);
end;
endfunction
|
github
|
ChamanAgrawal/ESO208-master
|
problem-2.m
|
.m
|
ESO208-master/assignment-3/problem-2.m
| 1,113 |
utf_8
|
fa620ada9cc88fd354292ba91eaeb666
|
clear;
fprintf("Give your no. of data and data points in a file named 'input2.txt'\n");
m= input("Please enter the degree of the polynomial for regression \n");
fid = fopen("input2.txt");
line =fgetl(fid);
n = sscanf(line, '%f ');
B = zeros(n,2);
for i=1:1:n
line = fgetl(fid);
B(i,1:1:2) = sscanf(line, '%f ');
end;
A=ones(m,m);
function [s] = sum(B,k,n,p)
s=0;
for i=1:n
s=s+(B(i,k).^p);
end
end
for i=1:m+1
k=i-1;
for j=1:m+1
[s]=sum(B,1,n,k+j-1);
A(i,j)=s;
end
end
R = ones(m+1,1);
for i=1:m+1
k=i-1;
s2=0;
for j=1:n
s2=s2+(B(j,1).^k)*B(j,2);
end
R(i,1)=s2;
end
C = A\R;
poly=@(t) 0;
for i=1:m+1
poly=@(t) poly(t) + C(i)*(t.^(i-1));
end
fplot(poly,[B(1,1),B(n,1)+0.1],'color','b'); hold on;
plot(B(:,1),B(:,2),'x','color','r')
for i=1:n
yeval(i)= feval(poly,B(i,1));
end
[fbar] = sum(B,2,n,0)/n;
s3=0;
for i=1:n
s3=s3+(B(i,2)-fbar).^2;
end
St=s3;
s3=0;
for i=1:n
s3=s3+(B(i,2)-yeval(i)).^2;
end
Sr=s3;
r = ((St-Sr)/St);
fileId = fopen('output2.txt','w');
fprintf(fileId,"Coefficient are :\n");
fprintf(fileId,'%f \n',C);
fprintf(fileId,'R-sq is : %f',r);
fclose(fileId);
|
github
|
ChamanAgrawal/ESO208-master
|
polynomial.m
|
.m
|
ESO208-master/assignment-3/polynomial.m
| 1,130 |
utf_8
|
b281a72640042e9ffd5c9e804f677ba9
|
## Copyright (C) 2017 Chaman Agrawal
##
## This program is free software; you can redistribute it and/or modify it
## under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 3 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program. If not, see <http://www.gnu.org/licenses/>.
## -*- texinfo -*-
## @deftypefn {Function File} {@var{retval} =} polynomial (@var{input1}, @var{input2})
##
## @seealso{}
## @end deftypefn
## Author: Chaman Agrawal <chaman@pc>
## Created: 2017-10-12
function [y] = polynomial (x,B ,n,m)
P = ones(n,1);
for i=1:n
for j=1:n
if(i~=j)
P(i,1)=P(i,1).*(x-B(j,1))/(B(i,1)-B(j,1));
end;
end;
end;
y=0;
for i=1:n
y=y+B(i,2)*P(i,1);
end;
endfunction
|
github
|
Abakumov/MLIB-master
|
wiggle.m
|
.m
|
MLIB-master/FUB/wiggle.m
| 17,031 |
utf_8
|
229f4636f5facd3d8445ca7d46c27de5
|
%WIGGLE Display data as wiggles.
% WIGGLE(C) displays matrix C as wiggles plus filled lobes, which is a
% common display for seismic data or any oscillatory data. A WIGGLE
% display is similar to WATERFALL, except that the Z heights are
% projected onto the horizontal plane, meaning that a WIGGLE display is
% actually a 2D display.
%
% WIGGLE(C) plots each column of C as curves vertically. How much the
% deviation is from the jth vertical is given by ith row. It C(i,j) is
% positive then the curve bends to the right, otherwise it bends to the
% left. Best visual effect is achieved when each column has no DC
% component, i.e., when its sum is zero, or at least close to it.
%
% WIGGLE(X,Y,C), where X and Y are vectors, rescale the axes to match X
% and Y values. When WIGGLE has one or three input, its usage is very
% similar to IMAGE or IMAGESC, except for WIGGLE's properties, described
% below.
%
% WIGGLE(...,S) allows some control of wiggles properties, in which S is
% a string with up to six characters, each one setting up a property,
% which can be Extrusion, Polarity, Direction, Wiggle Color and Lobes
% Color.
%
% Extrusion: '0', '1', ..., '9'
% It is how much a wiggle overlaps its neighbor. The default, '0',
% means there is no overlap. For instance, E='1' means that a
% wiggle overlaps only one neighbor and so on. Observe that only
% positve numbers are allowed.
%
% Polarity: '+' or '-'
% It defines which side of the wiggle is going to be filled.
% Polarity '+' (default) means that the positive lobes are filled,
% while '-' means that the negative lobes are filled.
%
% Wiggles Direction: 'v' or ' h'
% It specifies if the wiggles are vertical ('v'), which is the default,
% or horizontal ('h').
%
% Wiggles Color: 'b', 'g', 'r', 'c', 'm', 'y', 'k', 'w' or 'i'
% It defines the wiggle color. This property uses the same color key
% as in function PLOT. The default is black, i.e., 'k'. In order to
% suppress the wiggle, the character 'o' must be used. Options 'i',
% invisible, means that no wiggle is displayed.
%
% Lobes color: 'B', 'G', 'R', 'C', 'M', 'Y', 'K', 'W', 'X', '*' or 'I'
% It defines filling color for the right and left lobes. This property
% uses mostly the same color key as used in command PLOT, but in
% uppercase.
% The order of preference is right before left lobes, meaning that if
% only one character is given, the right lobes are painted with the
% corresponding color and the left lobes are invisible. In this way,
% the default is left lobes invisible and right lobes in black, i.e.,
% the string contains 'K' or 'IK'. Notice that a single 'I' implies
% that both lobes are invisible, because by default the left lobes are
% already invisible. If two capital characters are given, the first
% one defines the color of the left lobes and the second one of the
% right lobes.
% There are still two special coloring options which use the current
% figure colormap: '*' means that the lobes ares filled with a variable
% color that is horizontally layered and 'X' means that the lobes are
% filled with a variable color that is vertically layered.
%
% Note that the characters that build string S can be given in any
% order, but respecting the range and precedence of each propetry:
%
% Extrusion Polarity Direction Color
% Wiggles Lobes
% 0 - (default) + - right lobe v - vertical b blue B
% 1 - - left lobe h - horizontal g green G
% 2 r red R
% ... c cyan C
% m magenta M
% y yellow Y
% k black K
% w white W
% i invisible I
% colormap_h X
% colormap_v *
%
% Examples
% C = 2*rand(200,20) - 1;
% D = filter([1,1,1],1,C);
% figure(1); clf
% subplot(131); wiggle(D); title('default: right lobes in black')
% subplot(132); wiggle(D, '-'); title('left lobes in black')
% subplot(133); wiggle(D, 'yBR'); title('magenta lines, blue and red lobes')
% figure(2); clf
% subplot(311); wiggle(D', 'h'); title('Horizontal wiggles')
% subplot(312); wiggle(D', 'hB'); title('Horizontal wiggles with blue lobes')
% subplot(313); wiggle(D', 'hbMR'); title('Hor. wiggles, blue lines with magenta and red lobes')
% figure(3); clf
% subplot(131); wiggle(D, 'BR'); title('Blue and red lobes')
% subplot(132); wiggle(D, 'XX'); title('Horizontally filled colormapped lobes')
% subplot(133); wiggle(D, '1.5**'); title('Vertically filled colormapped lobes with 1.5 of extrusion')
%
% See also IMAGESC, IMAGE, WATERFALL, PLOT, LINESPEC
% by Rodrigo S. Portugal ([email protected])
% last revision: 18/10/2012
% TODO:
% 1) Implement the invisible option (DONE)
% 2) Implement the variable color option (DONE)
% 3) Implement wiggles overlaid imagesc (DONE)
% 3) Pair-wise options for fine tuning of properties (NOT YET)
% 3) Inspect the code (DONE)
% 4) Optimize (+/-)
% 5) Test examples (DONE)
function wiggle(varargin)
switch (nargin)
case 0
error('Too few input arguments.');
% Only data
case 1
data = check_data(varargin{1});
[nr,nc] = size(data);
xr = 1:nr;
xc = 1:nc;
prop = '';
% Data and properties
case 2
data = check_data(varargin{1});
[nr,nc] = size(data);
xr = 1:nr;
xc = 1:nc;
prop = check_properties(varargin{2});
% Domain vectors and data
case 3
xr = check_data(varargin{1});
xc = check_data(varargin{2});
data = check_data(varargin{3});
prop = '';
% Domain vectors, data and properties
case 4
xr = check_data(varargin{1});
xc = check_data(varargin{2});
data = check_data(varargin{3});
prop = check_properties(varargin{4});
otherwise
error('Too many input arguments.');
end
[extr, pol, dir, wcol, vcoll, vcolr] = extract_properties(prop);
wiggleplot(data, xr, xc, extr, wcol, vcoll, vcolr, dir, pol)
end
%--------------------------------------------------------------------------
function data = check_data(v)
if isnumeric(v),
data = v;
else
error('Wiggle: value must be numeric');
end
end
%--------------------------------------------------------------------------
function prop = check_properties(v)
if ischar(v)
prop = v;
else
error('Wiggle: properties must be a string.');
end
end
%--------------------------------------------------------------------------
function check_rgb(color)
if any(isnan(color)) || any(color > 1) || ...
size(color,1) ~= 1 || size(color,2) ~= 3
error(['Wiggle: color must be a numeric 1 x 3 matrix, '...
'following RGB system'])
end
end
%--------------------------------------------------------------------------
function [extr, pol, dir, wcol, vcoll, vcolr] = extract_properties(prop)
wcol = 'k';
vcol = 'k';
dir = 0;
pol = 1;
extr = extractfloat(prop);
if isnan(extr), extr = 1.0; end
indv = 1;
for ip = 1:length(prop)
p = prop(ip);
if p == '+' || p == '-'
if p == '+'
pol = 1;
else
pol = -1;
end
continue
end
if p == 'h' || p == 'v' || p == 'H' || p == 'V'
if p == 'v' || p == 'V',
dir = 0;
else
dir = 1;
end
continue
end
if p == 'b' || p == 'g' || p == 'r' || p == 'c' || p == 'm' || ...
p == 'y' || p == 'k' || p == 'w' || p == 'i'
wcol = p;
continue
end
if p == 'B' || p == 'G' || p == 'R' || p == 'C' || p == 'M' || ...
p == 'Y' || p == 'K' || p == 'W' || p == 'I' || p == 'X' || p == '*'
vcol(indv) = lower(p);
indv = 2;
continue
end
end
wcol = str2rgb(wcol);
if length(vcol) == 2
vcoll = str2rgb(vcol(1));
vcolr = str2rgb(vcol(2));
else
vcoll = NaN;
vcolr = str2rgb(vcol(1));
end
end
%--------------------------------------------------------------------------
function f = extractfloat(str)
fs = blanks(length(str));
foundpoint = false;
count = 1;
for i = 1: length(str)
cs = str(i);
if cs == '.' && ~foundpoint
fs(count) = cs;
count = count + 1;
foundpoint = true;
continue
end
c = str2double(cs);
if ~isnan(c) && isreal(c)
fs(count) = cs;
count = count + 1;
end
end
f = str2double(fs);
end
%--------------------------------------------------------------------------
function rgb = str2rgb(s)
switch s
case 'r'
rgb = [1, 0, 0];
case 'g'
rgb = [0, 1, 0];
case 'b'
rgb = [0, 0, 1];
case 'c'
rgb = [0, 1, 1];
case 'm'
rgb = [1, 0, 1];
case 'y'
rgb = [1, 1, 0];
case 'k'
rgb = [0, 0, 0];
case 'w'
rgb = [1, 1, 1];
case 'i'
rgb = NaN;
case 'x'
rgb = 1;
case '*'
rgb = 2;
otherwise
rgb = NaN;
end
end
%--------------------------------------------------------------------------
% WIGGLEPLOT plots seismic data as wiggles and variable area
% WIGGLEPLOT(data, y, x, k, wc, vcl, vcr, d, p)
% INPUT DESCRIPTION TYPE SIZE
% data oscilatory data matrix (nx x nt)
% y vertical coordinates vector ( 1 x ny)
% x horizontal coordinates vector ( 1 x nx)
% k extrusion scalar ( 1 x 1 )
% wc wiggle color matrix ( 1 x 3 )
% wc=0 supress the wiggle
% vcl variable area color (left lobe) matrix ( 1 x 3 )
% vcl=0 or NaN suppress the left variable area
% vcr variable area color matrix ( 1 x 3 )
% vcr=0 or NaN suppress the right variable area
% d wiggle direction scalar ( 1 x 1 )
% d=0 for vertical
% d=1 for horizontal
% p polarity scalar ( 1 x 1 )
% p=1 (SEG convention) positive area
% p=-1 (EAGE convention) negative area
%
% See also IMAGESC, IMAGE
function wiggleplot(data, xr, xc, extr, wcol, vcoll, vcolr, dir, pol)
[nrows,ncols] = size(data);
if ncols ~= length(xc) || nrows ~= length(xr)
error('Input data must have compatible dimensions');
end
if dir == 1
data = data';
extr = -extr;
aux = xc;
xc = xr;
xr = aux;
end
nxr = length(xr);
nxc = length(xc);
if nxc > 1,
dx = xc(2)-xc(1);
else
dx = 1;
end
% ir = nxr-1:-1:2;
plot_var = true;
plot_val = true;
if length(vcoll) == 1
if isnan(vcoll) || vcoll == 0
plot_val = false;
elseif vcoll ~= 1 && vcoll ~= 2
error('wiggleplot: color not recognized.')
end
else
check_rgb(vcoll)
end
if length(vcolr) == 1
if isnan(vcolr) || vcolr == 0
plot_var = false;
elseif vcolr ~= 1 && vcolr ~= 2
error('wiggleplot: color not recognized.')
end
else
check_rgb(vcolr)
end
plot_w = true;
if length(wcol) == 1
if isnan(wcol) || wcol == 0
plot_w = false;
else
error('wiggleplot: color not recognized.')
end
else
check_rgb(wcol)
end
if pol == -1,
data = -data;
end
count = make_counter(nxc, dir);
[plotdir, patchdirl, patchdirr] = select_functions(dir, plot_w, plot_val, plot_var);
scale = pol * extr * dx / (max(data(:))+eps);
hold on
xwig = zeros(nxc,2*nxr+1);
ywig = zeros(nxc,2*nxr+1);
if vcoll == 2
chunk = zeros(nxc,4*nxr+3);
else
chunk = zeros(nxc,2*nxr+2);
end
xval = chunk; yval = chunk; %cval = chunk;
xvar = chunk; yvar = chunk; %cvar = chunk;
for ic = count(1):count(2):count(3)
[xr1, d, sl1, sr1, ~, ~] = make_lines(xr, data(:,ic)');
xr2 = xr1;
sr2 = sr1;
sl2 = sl1;
if vcolr == 1
colr = [0, d, 0];
elseif vcolr == 2
colr = [0, d, 0, fliplr(d), 0];
xr2 = [xr1, fliplr(xr1(1:end-1))];
sr2 = [sr1, zeros(1,length(sr1)-1)];
else
colr = vcolr;
end
xvar(ic,:) = xc(ic) + scale * sr2;
yvar(ic,:) = xr2;
cvar(ic,:) = colr;
if vcoll == 1
coll = [0, d, 0];
elseif vcoll == 2
coll = [0, d, 0, fliplr(d), 0];
xr2 = [xr1, fliplr(xr1(1:end-1))];
sl2 = [sl1, zeros(1,length(sl1)-1)];
else
coll = vcoll;
end
xval(ic,:) = xc(ic) + scale * sl2;
yval(ic,:) = xr2;
cval(ic,:) = coll;
xwig(ic,:) = [xc(ic) + scale * d, NaN];
ywig(ic,:) = [xr1(2:end-1), NaN];
end
patchdirl(xval', yval', cval');
patchdirr(xvar', yvar', cvar');
plotdir(xwig,ywig,wcol);
hold off
if dir == 1,
axis([min(xr), max(xr), min(xc) - extr * dx, max(xc) + extr * dx])
else
axis([min(xc) - extr * dx, max(xc) + extr * dx, min(xr), max(xr)])
end
set(gca,'NextPlot','replace', 'XDir','normal','YDir','reverse')
end
%--------------------------------------------------------------------------
function counter = make_counter(nxc, dir)
if dir == 1,
ic_first = 1;
ic_last = nxc;
ic_step = 1;
else
ic_first = nxc;
ic_last = 1;
ic_step = -1;
end
counter = [ic_first, ic_step, ic_last];
end
%--------------------------------------------------------------------------
function [fw, fval, fvar] = select_functions(dir, plot_w, plot_val, plot_var)
fw = @plot_vert;
fval = @patch_vert;
fvar = @patch_vert;
if dir == 1,
fw = @plot_hor;
fval = @patch_hor;
fvar = @patch_hor;
end
if plot_w == false
fw = @donothing;
end
if plot_val == false
fval = @donothing;
end
if plot_var == false
fvar = @donothing;
end
if (plot_val == false) && (plot_var == false) && (plot_w == false),
disp('wiggle warning: neither variable area and wiggles are displayed');
end
end
%--------------------------------------------------------------------------
function [t1, d, sl, sr, ul, ur] = make_lines(t, s)
nt = length(t);
dt = t(2) - t(1);
ds = s(2:nt)-s(1:nt-1);
r = ((s(2:nt)<0) .* (s(1:nt-1)>0)) + ((s(2:nt)>0) .* (s(1:nt-1)<0));
a = r .* s(2:nt)./(ds+eps) + (1-r).*0.5;
tc(1:2:2*nt-1) = t;
tc(2:2:2*nt-2) = t(2:nt) - dt * a;
sc(1:2:2*nt-1) = s;
sc(2:2:2*nt-2) = 0.5*(s(1:nt-1)+ s(2:nt)).*(1-r);
t1 = [t(1), tc, t(nt), t(nt)];
d0 = [0, sc, s(nt), 0];
dr = [max(sc), sc, s(nt), max(sc)];
dl = [min(sc), sc, s(nt), min(sc)];
sl = min(0,d0);
sr = max(0,d0);
ul = min(0,dl);
ur = max(0,dr);
d = d0(2:end-1);
end
%--------------------------------------------------------------------------
function donothing(~,~,~)
end
%--------------------------------------------------------------------------
function ph = plot_vert(x,y,col)
x = reshape(x',1,numel(x));
y = reshape(y',1,numel(y));
ph = line(x,y,'linewidth',0.25,'color', col);
end
%--------------------------------------------------------------------------
function ph = plot_hor(x,y,col)
x = reshape(x',1,numel(x));
y = reshape(y',1,numel(y));
ph = line(y,x,'linewidth',0.25,'color', col);
end
%--------------------------------------------------------------------------
function fh = patch_vert(x,y,col)
if size(col,1) == 3,
col = col(:,1)';
end
fh = patch(x,y,col,'edgecolor','none');
hold on
end
%--------------------------------------------------------------------------
function fh = patch_hor(x,y,col)
if size(col,1) == 3,
col = col(:,1)';
end
fh = patch(y,x,col,'edgecolor','none');
hold on
end
|
github
|
Abakumov/MLIB-master
|
trace_inverse2D.m
|
.m
|
MLIB-master/BASIC/trace_inverse2D.m
| 3,641 |
utf_8
|
5f52dc6926bf51065e644b828e38524b
|
function ray = trace_inverse2D(Gold, S, alpha, t0, velmod)
% Ivan Abakumov
% Ray tracer in 2D isotropic medium
% Input: G, S, velmod, alpha
% Output: ray = matrix[5xGnt]
% arrays: [x, z, px, pz, t]
% Method Runge-Kutt, 4th order
%% tmp
% clear all; close all; clc;
% mlibfolder = '/home/zmaw/u250128/Desktop/MLIB';
% path(path, mlibfolder);
% addmypath;
% current_folder = pwd;
%
% G=GridClass;
%
% % [m] [m] [m] [s]
% G.x0 = -2475; G.y0 = 0; G.z0 = -5000; G.t0 = 0.00; % initial point
% G.nx = 1000; G.ny = 1; G.nz = 800; G.nt = 1000; % grid size
% G.dx = 25; G.dy = 25; G.dz = 25; G.dt = 0.007; % grid step (meter)
%
%
% G.gridInfo;
% G.setGrid;
% Gold = oldGrid(G);
%
% velmod = zeros(G.nx, G.nz);
%
% velmod(:, 1:240)=1500;
% for i=241:390
% velmod(:, i)=velmod(:,i-1)+8.0;
% end
% for i=391:G.nz
% velmod(:,i)=velmod(:,390);
% end
%
% S = [5000 0];
% alpha = pi/6;
%% Read input
Gox=Gold(1); Goy=Gold(2); Goz=Gold(3); Got=Gold(10);
Gnx=Gold(4); Gny=Gold(5); Gnz=Gold(6); Gnt=Gold(11);
Gdx=Gold(7); Gdy=Gold(8); Gdz=Gold(9); Gdt=Gold(12);
Gmx = Gox + (Gnx-1)*Gdx;
Gmy = Goy + (Gny-1)*Gdy;
Gmz = Goz + (Gnz-1)*Gdz;
Gmt = Got + (Gnt-1)*Gdt;
xx = Gox:Gdx:Gmx;
yy = Goy:Gdy:Gmy;
zz = Goz:Gdz:Gmz;
tt = Got:Gdt:Gmt;
%% Find derivatives of velocity
dvdx = zeros(size(velmod));
dvdz = zeros(size(velmod));
dvdx(1:end-1,:) = diff(velmod,1,1)/Gdx;
dvdx(end,:) = dvdx(end-1,:);
dvdz(:,1:end-1) = diff(velmod,1,2)/Gdz;
dvdz(:,end) = dvdz(:,end-1);
%% Find Hamiltonian
y=zeros(5, Gnt+1);
% find velocity in the origin of the ray
v0 = velmod(x2grid(S(1),Gox,Gdx,Gnx), x2grid(S(2),Goz,Gdz,Gnz));
% set initial values
y(1, 1) = S(1);
y(2, 1) = S(2);
y(3, 1) = sin(alpha)/v0; % y(3:4) is slowness components
y(4, 1) = cos(alpha)/v0; % only direction is important
y(5 ,1) = t0;
i=1; t=t0;
while t>0 && y(1, i)>=Gox && y(1, i)<=Gmx && y(2, i)>=Goz && y(2, i)<=Gmz
k1 = funct(y(1:4, i), velmod, dvdx, dvdz, Gold);
k2 = funct(y(1:4, i)+Gdt*k1/2, velmod, dvdx, dvdz, Gold);
k3 = funct(y(1:4, i)+Gdt*k2/2, velmod, dvdx, dvdz, Gold);
k4 = funct(y(1:4, i)+Gdt*k3, velmod, dvdx, dvdz, Gold);
y(1:4, i+1) = y(1:4, i) + Gdt*(k1+2*k2+2*k3+k4)/6;
y(5, i+1) = y(5, i) - Gdt;
t = t - Gdt;
i = i+1;
end;
if abs(y(5,i-1)) < Gdt
dy = (y(:,i) - y(:,i-1))/Gdt;
y(:, i) = y(:,i-1) + y(5,i-1)*dy;
ray = y(1:5, 1:i);
else
ray = y(1:5, 1:i-1);
end
end
function f=funct(y, velmod, dvdx, dvdz, Gold)
f = zeros(4,1);
Gox=Gold(1); Goy=Gold(2); Goz=Gold(3); Got=Gold(10);
Gnx=Gold(4); Gny=Gold(5); Gnz=Gold(6); Gnt=Gold(11);
Gdx=Gold(7); Gdy=Gold(8); Gdz=Gold(9); Gdt=Gold(12);
indx = x2grid(y(1),Gox,Gdx,Gnx);
indz = x2grid(y(2),Goz,Gdz,Gnz);
v0 = velmod(indx,indz);
dvdx0 = dvdx(indx,indz);
dvdz0 = dvdz(indx,indz);
% see Cherveny, Seismic ray theory, Eq. 3.1.14
% dx
f(1) = v0^2*y(3); % dx/dt = v^2*p_x
f(2) = v0^2*y(4); % dz/dt = v^2*p_z
% dp
f(3) = -dvdx0/v0; % dp/dx = -1/v*dv/dx
f(4) = -dvdz0/v0; % dp/dz = -1/v*dv/dz
end
|
github
|
Abakumov/MLIB-master
|
trace_inverse3D.m
|
.m
|
MLIB-master/BASIC/trace_inverse3D.m
| 3,983 |
utf_8
|
0fc867bbf4844a7d0ded0d0cab80a723
|
function ray = trace_inverse3D(Gold, S, alpha, beta, t0, velmod)
% Ivan Abakumov
% Ray tracer in 2D isotropic medium
% Input: G, S, velmod, alpha
% Output: ray = matrix[5xGnt]
% arrays: [x, z, px, pz, t]
% Method Runge-Kutt, 4th order
%% tmp
% clear all; close all; clc;
% mlibfolder = '/home/zmaw/u250128/Desktop/MLIB';
% path(path, mlibfolder);
% addmypath;
% current_folder = pwd;
%
% G=GridClass;
%
% % [m] [m] [m] [s]
% G.x0 = -2475; G.y0 = 0; G.z0 = -5000; G.t0 = 0.00; % initial point
% G.nx = 1000; G.ny = 1; G.nz = 800; G.nt = 1000; % grid size
% G.dx = 25; G.dy = 25; G.dz = 25; G.dt = 0.007; % grid step (meter)
%
%
% G.gridInfo;
% G.setGrid;
% Gold = oldGrid(G);
%
% velmod = zeros(G.nx, G.nz);
%
% velmod(:, 1:240)=1500;
% for i=241:390
% velmod(:, i)=velmod(:,i-1)+8.0;
% end
% for i=391:G.nz
% velmod(:,i)=velmod(:,390);
% end
%
% S = [5000 0];
% alpha = pi/6;
%% Read input
Gox=Gold(1); Goy=Gold(2); Goz=Gold(3); Got=Gold(10);
Gnx=Gold(4); Gny=Gold(5); Gnz=Gold(6); Gnt=Gold(11);
Gdx=Gold(7); Gdy=Gold(8); Gdz=Gold(9); Gdt=Gold(12);
Gmx = Gox + (Gnx-1)*Gdx;
Gmy = Goy + (Gny-1)*Gdy;
Gmz = Goz + (Gnz-1)*Gdz;
Gmt = Got + (Gnt-1)*Gdt;
%% Find derivatives of velocity
dvdx = zeros(size(velmod));
dvdy = zeros(size(velmod));
dvdz = zeros(size(velmod));
dvdx(1:end-1,:,:) = diff(velmod,1,1)/Gdx;
dvdx(end,:,:) = dvdx(end-1,:,:);
dvdy(:,1:end-1,:) = diff(velmod,1,2)/Gdy;
dvdy(:,end,:) = dvdy(:,end-1,:);
dvdz(:,:,1:end-1) = diff(velmod,1,3)/Gdz;
dvdz(:,:,end) = dvdz(:,:,end-1);
%% Find Hamiltonian
y=zeros(7, Gnt+1);
% find velocity in the origin of the ray
v0 = velmod(x2grid(S(1),Gox,Gdx,Gnx), x2grid(S(2),Goy,Gdy,Gny),x2grid(S(3),Goz,Gdz,Gnz));
% set initial values
y(1, 1) = S(1);
y(2, 1) = S(2);
y(3, 1) = S(3);
y(4, 1) = sin(alpha)*cos(beta)/v0; % y(4:6) is slowness components
y(5, 1) = sin(alpha)*sin(beta)/v0; % only direction is important
y(6, 1) = cos(alpha)/v0;
y(7 ,1) = t0;
i=1; t=t0;
while t>0 && y(1, i)>=Gox && y(1, i)<=Gmx && y(2, i)>=Goy && y(2, i)<=Gmy && y(3, i)>=Goz && y(3, i)<=Gmz
k1 = funct(y(1:6, i), velmod, dvdx, dvdy, dvdz, Gold);
k2 = funct(y(1:6, i)+Gdt*k1/2, velmod, dvdx, dvdy, dvdz, Gold);
k3 = funct(y(1:6, i)+Gdt*k2/2, velmod, dvdx, dvdy, dvdz, Gold);
k4 = funct(y(1:6, i)+Gdt*k3, velmod, dvdx, dvdy, dvdz, Gold);
y(1:6, i+1) = y(1:6, i) + Gdt*(k1+2*k2+2*k3+k4)/6;
y(7, i+1) = y(7, i) - Gdt;
t = t - Gdt;
i = i+1;
end;
if abs(y(7,i-1)) < Gdt
dy = (y(:,i) - y(:,i-1))/Gdt;
y(:, i) = y(:,i-1) + y(7,i-1)*dy;
ray = y(1:7, 1:i);
else
ray = y(1:7, 1:i-1);
end
end
function f=funct(y, velmod, dvdx, dvdy, dvdz, Gold)
f = zeros(6,1);
Gox=Gold(1); Goy=Gold(2); Goz=Gold(3);
Gnx=Gold(4); Gny=Gold(5); Gnz=Gold(6);
Gdx=Gold(7); Gdy=Gold(8); Gdz=Gold(9);
indx = x2grid(y(1),Gox,Gdx,Gnx);
indy = x2grid(y(2),Goy,Gdy,Gny);
indz = x2grid(y(3),Goz,Gdz,Gnz);
v0 = velmod(indx,indy,indz);
dvdx0 = dvdx(indx,indy,indz);
dvdy0 = dvdy(indx,indy,indz);
dvdz0 = dvdz(indx,indy,indz);
% see Cherveny, Seismic ray theory, Eq. 3.1.14
% dx
f(1) = v0^2*y(4); % dx/dt = v^2*p_x
f(2) = v0^2*y(5); % dy/dt = v^2*p_y
f(3) = v0^2*y(6); % dz/dt = v^2*p_z
% dp
f(4) = -dvdx0/v0; % dp/dx = -1/v*dv/dx
f(5) = -dvdy0/v0; % dp/dy = -1/v*dv/dy
f(6) = -dvdz0/v0; % dp/dz = -1/v*dv/dz
end
|
github
|
Abakumov/MLIB-master
|
makeColorMap.m
|
.m
|
MLIB-master/BASIC/makeColorMap.m
| 2,632 |
utf_8
|
1ae86f03780f8e278516898b711ebf2b
|
function cMap = makeColorMap(varargin)
%% MAKECOLORMAP makes smoothly varying colormaps
% a = makeColorMap(beginColor, middleColor, endColor, numSteps);
% a = makeColorMap(beginColor, endColor, numSteps);
% a = makeColorMap(beginColor, middleColor, endColor);
% a = makeColorMap(beginColor, endColor);
%
% all colors are specified as RGB triples
% numSteps is a scalar saying howmany points are in the colormap
%
% Examples:
%
% peaks;
% a = makeColorMap([1 0 0],[1 1 1],[0 0 1],40);
% colormap(a)
% colorbar
%
% peaks;
% a = makeColorMap([1 0 0],[0 0 1],40);
% colormap(a)
% colorbar
%
% peaks;
% a = makeColorMap([1 0 0],[1 1 1],[0 0 1]);
% colormap(a)
% colorbar
%
% peaks;
% a = makeColorMap([1 0 0],[0 0 1]);
% colormap(a)
% colorbar
% Reference:
% A. Light & P.J. Bartlein, "The End of the Rainbow? Color Schemes for
% Improved Data Graphics," Eos,Vol. 85, No. 40, 5 October 2004.
% http://geography.uoregon.edu/datagraphics/EOS/Light&Bartlein_EOS2004.pdf
defaultNum = 100;
errorMessage = 'See help MAKECOLORMAP for correct input arguments';
if nargin == 2 %endPoints of colormap only
color.start = varargin{1};
color.middle = [];
color.end = varargin{2};
color.num = defaultNum;
elseif nargin == 4 %endPoints, midPoint, and N defined
color.start = varargin{1};
color.middle = varargin{2};
color.end = varargin{3};
color.num = varargin{4};
elseif nargin == 3 %endPoints and num OR endpoints and Mid
if numel(varargin{3}) == 3 %color
color.start = varargin{1};
color.middle = varargin{2};
color.end = varargin{3};
color.num = defaultNum;
elseif numel(varargin{3}) == 1 %numPoints
color.start = varargin{1};
color.middle = [];
color.end = varargin{2};
color.num = varargin{3};
else
error(errorMessage)
end
else
error(errorMessage)
end
if color.num <= 1
error(errorMessage)
end
if isempty(color.middle) %no midPoint
cMap = interpMap(color.start, color.end, color.num);
else %midpointDefined
[topN, botN] = sizePartialMaps(color.num);
cMapTop = interpMap(color.start, color.middle, topN);
cMapBot = interpMap(color.middle, color.end, botN);
cMap = [cMapTop(1:end-1,:); cMapBot];
end
function cMap = interpMap(colorStart, colorEnd, n)
for i = 1:3
cMap(1:n,i) = linspace(colorStart(i), colorEnd(i), n);
end
function [topN, botN] = sizePartialMaps(n)
n = n + 1;
topN = ceil(n/2);
botN = floor(n/2);
% Copyright 2008 - 2009 The MathWorks, Inc.
|
github
|
Abakumov/MLIB-master
|
exel2d.m
|
.m
|
MLIB-master/EL2D/exel2d.m
| 4,444 |
utf_8
|
b220dcb223855035cccf81d9893c933b
|
function [p, ux, uz, uxx, uzz, uxz, uzx] = exel2d(rho,vp,vs,xs,zs,xl,zl,wf,fr,stype)
nfr = length(fr);
ifr = find(fr>0);
nsh = length(xs);
om = fr(ifr).*(2*pi);
if isvector(xl)
nxl = length(xl);
nzl = length(zl);
p = single(zeros(nfr,nxl,nzl,nsh));
ux = p; uz = p; uxx = p; uzz = p; uxz = p; uzx = p;
for ish=1:nsh
for izl=1:nzl
for ixl=1:nxl
x = xl(ixl)-xs(ish);
z = -(zl(izl)-zs(ish));
[pf,uxf,uzf,uxxf,uzzf,uxzf,uzxf] = wavefield(x,z,rho,vp,vs,om,wf(ifr),stype);
p (ifr,ixl,izl,ish) = pf;
ux (ifr,ixl,izl,ish) = uxf;
uz (ifr,ixl,izl,ish) = uzf;
uxx(ifr,ixl,izl,ish) = uxxf;
uzz(ifr,ixl,izl,ish) = uzzf;
uxz(ifr,ixl,izl,ish) = uxzf;
uzx(ifr,ixl,izl,ish) = uzxf;
end
end
end
elseif size(xl,1)==2
nrec = size(xl,2);
p = single(zeros(nfr,nrec,nsh));
ux = p; uz = p; uxx = p; uzz = p; uxz = p; uzx = p;
for ish=1:nsh
for irec=1:nrec
x = xl(1,irec)-xs(ish);
z = -(xl(2,irec)-zs(ish));
[pf,uxf,uzf,uxxf,uzzf,uxzf,uzxf] = wavefield(x,z,rho,vp,vs,om,wf(ifr),stype);
p (ifr,irec,ish) = pf;
ux (ifr,irec,ish) = uxf;
uz (ifr,irec,ish) = uzf;
uxx(ifr,irec,ish) = uxxf;
uzz(ifr,irec,ish) = uzzf;
uxz(ifr,irec,ish) = uxzf;
uzx(ifr,irec,ish) = uzxf;
end
end
end
end
function [p,ux,uz,uxx,uzz,uxz,uzx] = wavefield(x,z,rho,vp,vs,om,wf,stype)
x2 = x^2;
z2 = z^2;
r2 = x2+z2;
r = sqrt(r2);
vp2 = vp^2;
vs2 = vs^2;
if r<eps(r)
p = 0.*om;
ux = p; uz = p; uxx = p; uzz = p; uxz = p; uzx = p;
return;
end
rkp = om.*r./vp;
irkp = rkp.^-1;
rks = om.*r./vs;
irks = rks.^-1;
h0p = besselh(0,1,rkp);
h1p = besselh(1,1,rkp);
h2p = besselh(2,1,rkp);
h0s = besselh(0,1,rks);
h1s = besselh(1,1,rks);
h2s = besselh(2,1,rks);
gp1 = h1p.*irkp./vp2;
gp2 = h0p./vp2;
gs1 = h1s.*irks./vs2;
gs2 = h0s./vs2;
gp1x = -h2p.*(x/r2/vp2);
gp1z = -h2p.*(z/r2/vp2);
gp2x = -h1p.*rkp.*(x/r2/vp2);
gp2z = -h1p.*rkp.*(z/r2/vp2);
gs1x = -h2s.*(x/r2/vs2);
gs1z = -h2s.*(z/r2/vs2);
gs2x = -h1s.*rks.*(x/r2/vs2);
gs2z = -h1s.*rks.*(z/r2/vs2);
C = wf.*(1i/4/rho);
switch stype
case 1
ux = C.*(gp1 + (x2/r2).*gp2 + ((x2-z2)/r2).*gs1 + (z2/r2).*gs2);
uz = (C.*(x*z/r2)).*(2.*gp1 - gp2 - 2.*gs1 + gs2);
uzz = -C.*((x*z/r2).*(2.*gp1z - gp2z - 2.*gs1z + gs2z) + (x*(x2-z2)/r2^2).*(2.*gp1 - gp2 - 2.*gs1 + gs2));
uzx = C.*((x*z/r2).*(2.*gp1x - gp2x - 2.*gs1x + gs2x) + (z*(z2-x2)/r2^2).*(2.*gp1 - gp2 - 2.*gs1 + gs2));
uxz = -C.*(gp1z - (2*z*x2/r2^2).*gp2 + (x2/r2).*gp2z - (4*z*x2/r2^2).*gs1 + ((x2-z2)/r2).*gs1z + (2*z*x2/r2^2).*gs2 + (z2/r2).*gs2z);
uxx = C.*(gp1x - (2*x*z2/r2^2).*gp2 + (x2/r2).*gp2x + (4*x*z2/r2^2).*gs1 + ((x2-z2)/r2).*gs1x - (2*x*z2/r2^2).*gs2 + (z2/r2).*gs2x);
p = -(rho*vp2).*(uxx + uzz);
case 2
ux = (C.*(x*z/r2)).*(2.*gp1 - gp2 - 2.*gs1 + gs2);
uz = C.*(gp1 + (z2/r2).*gp2 + ((z2-x2)/r2).*gs1 + (x2/r2).*gs2);
uxx = C.*((x*z/r2).*(2.*gp1x - gp2x - 2.*gs1x + gs2x) + (z*(z2-x2)/r2^2).*(2.*gp1 - gp2 - 2.*gs1 + gs2));
uxz = -C.*((x*z/r2).*(2.*gp1z - gp2z - 2.*gs1z + gs2z) + (x*(x2-z2)/r2^2).*(2.*gp1 - gp2 - 2.*gs1 + gs2));
uzx = C.*(gp1x - (2*x*z2/r2^2).*gp2 + (z2/r2).*gp2x - (4*x*z2/r2^2).*gs1 + ((z2-x2)/r2).*gs1x + (2*x*z2/r2^2).*gs2 + (x2/r2).*gs2x);
uzz = -C.*(gp1z - (2*z*x2/r2^2).*gp2 + (z2/r2).*gp2z + (4*z*x2/r2^2).*gs1 + ((z2-x2)/r2).*gs1z - (2*z*x2/r2^2).*gs2 + (x2/r2).*gs2z);
p = -(rho*vp2).*(uxx + uzz);
otherwise
error('Unknown/non-implemented source type!');
end
end
|
github
|
Abakumov/MLIB-master
|
Get_traveltime_2D_exact.m
|
.m
|
MLIB-master/CRS/Get_traveltime_2D_exact.m
| 1,544 |
utf_8
|
8133283d9f09a49df83cd71f9acd1b94
|
function [T, Xr] = Get_traveltime_2D_exact(M, H, model)
% Calculate exact traveltime for PS or PP wave
% reflected from the circle by dihotomia
% Abakumov Ivan
% 1st April 2016
% [email protected]
% University of Hamburg
T = zeros(size(M));
Xr = zeros(size(M));
% alpha = model(1); % deg
% Rnip = model(2); % km
% Rn = model(3); % km
% Vp = model(4); % km/s
% Vs = model(5); % km/s
for i=1:size(M,1);
for j=1:size(M,2);
xg = M(i,j) + H(i,j);
xs = M(i,j) - H(i,j);
thetar = linspace(-pi, pi, 21);
for iter = 1:10
[xref, zref] = Get_2D_circle(model, thetar);
[t, ind] = min(Get_2D_traveltime(xs, xg, xref, zref, model));
minind = max(ind-1, 1);
maxind = min(ind+1, 21);
thetar = linspace(thetar(minind), thetar(maxind), 21);
end
T(i,j) = t;
Xr(i,j) = thetar(11);
end
end
end
function t = Get_2D_traveltime(xs, xg, xref, zref, model)
% see eq. D.9
Vp = model(4); % km/s
Vs = model(5); % km/s
t = sqrt((xs-xref).^2+zref.^2)/Vp + sqrt((xg-xref).^2+zref.^2)/Vs;
end
function [xref, zref] = Get_2D_circle(model, thetar)
% see eq. D.11
alpha = model(1); % deg
Rnip = model(2); % km
Rn = model(3); % km
R = Rn-Rnip;
xref = -Rn*sin(alpha) + R*sin(alpha - thetar);
zref = Rn*cos(alpha) - R*cos(alpha - thetar);
end
|
github
|
Abakumov/MLIB-master
|
pdftops.m
|
.m
|
MLIB-master/OTHER/Export_fig/pdftops.m
| 6,161 |
utf_8
|
5edac4bbbdae30223cb246a4ec7313d6
|
function varargout = pdftops(cmd)
%PDFTOPS Calls a local pdftops executable with the input command
%
% Example:
% [status result] = pdftops(cmd)
%
% Attempts to locate a pdftops executable, finally asking the user to
% specify the directory pdftops was installed into. The resulting path is
% stored for future reference.
%
% Once found, the executable is called with the input command string.
%
% This function requires that you have pdftops (from the Xpdf package)
% installed on your system. You can download this from:
% http://www.foolabs.com/xpdf
%
% IN:
% cmd - Command string to be passed into pdftops (e.g. '-help').
%
% OUT:
% status - 0 iff command ran without problem.
% result - Output from pdftops.
% Copyright: Oliver Woodford, 2009-2010
% Thanks to Jonas Dorn for the fix for the title of the uigetdir window on Mac OS.
% Thanks to Christoph Hertel for pointing out a bug in check_xpdf_path under linux.
% 23/01/2014 - Add full path to pdftops.txt in warning.
% 27/05/2015 - Fixed alert in case of missing pdftops; fixed code indentation
% 02/05/2016 - Added possible error explanation suggested by Michael Pacer (issue #137)
% 02/05/2016 - Search additional possible paths suggested by Jonas Stein (issue #147)
% 03/05/2016 - Display the specific error message if pdftops fails for some reason (issue #148)
% Call pdftops
[varargout{1:nargout}] = system([xpdf_command(xpdf_path()) cmd]);
end
function path_ = xpdf_path
% Return a valid path
% Start with the currently set path
path_ = user_string('pdftops');
% Check the path works
if check_xpdf_path(path_)
return
end
% Check whether the binary is on the path
if ispc
bin = 'pdftops.exe';
else
bin = 'pdftops';
end
if check_store_xpdf_path(bin)
path_ = bin;
return
end
% Search the obvious places
if ispc
paths = {'C:\Program Files\xpdf\pdftops.exe', 'C:\Program Files (x86)\xpdf\pdftops.exe'};
else
paths = {'/usr/bin/pdftops', '/usr/local/bin/pdftops'};
end
for a = 1:numel(paths)
path_ = paths{a};
if check_store_xpdf_path(path_)
return
end
end
% Ask the user to enter the path
errMsg1 = 'Pdftops not found. Please locate the program, or install xpdf-tools from ';
url1 = 'http://foolabs.com/xpdf';
fprintf(2, '%s\n', [errMsg1 '<a href="matlab:web(''-browser'',''' url1 ''');">' url1 '</a>']);
errMsg1 = [errMsg1 url1];
%if strncmp(computer,'MAC',3) % Is a Mac
% % Give separate warning as the MacOS uigetdir dialogue box doesn't have a title
% uiwait(warndlg(errMsg1))
%end
% Provide an alternative possible explanation as per issue #137
errMsg2 = 'If you have pdftops installed, perhaps Matlab is shaddowing it as described in ';
url2 = 'https://github.com/altmany/export_fig/issues/137';
fprintf(2, '%s\n', [errMsg2 '<a href="matlab:web(''-browser'',''' url2 ''');">issue #137</a>']);
errMsg2 = [errMsg2 url1];
state = 0;
while 1
if state
option1 = 'Install pdftops';
else
option1 = 'Issue #137';
end
answer = questdlg({errMsg1,'',errMsg2},'Pdftops error',option1,'Locate pdftops','Cancel','Cancel');
drawnow; % prevent a Matlab hang: http://undocumentedmatlab.com/blog/solving-a-matlab-hang-problem
switch answer
case 'Install pdftops'
web('-browser',url1);
case 'Issue #137'
web('-browser',url2);
state = 1;
case 'Locate pdftops'
base = uigetdir('/', errMsg1);
if isequal(base, 0)
% User hit cancel or closed window
break
end
base = [base filesep]; %#ok<AGROW>
bin_dir = {'', ['bin' filesep], ['lib' filesep]};
for a = 1:numel(bin_dir)
path_ = [base bin_dir{a} bin];
if exist(path_, 'file') == 2
break
end
end
if check_store_xpdf_path(path_)
return
end
otherwise % User hit Cancel or closed window
break
end
end
error('pdftops executable not found.');
end
function good = check_store_xpdf_path(path_)
% Check the path is valid
good = check_xpdf_path(path_);
if ~good
return
end
% Update the current default path to the path found
if ~user_string('pdftops', path_)
warning('Path to pdftops executable could not be saved. Enter it manually in %s.', fullfile(fileparts(which('user_string.m')), '.ignore', 'pdftops.txt'));
return
end
end
function good = check_xpdf_path(path_)
% Check the path is valid
[good, message] = system([xpdf_command(path_) '-h']); %#ok<ASGLU>
% system returns good = 1 even when the command runs
% Look for something distinct in the help text
good = ~isempty(strfind(message, 'PostScript'));
% Display the error message if the pdftops executable exists but fails for some reason
if ~good && exist(path_,'file') % file exists but generates an error
fprintf('Error running %s:\n', path_);
fprintf(2,'%s\n\n',message);
end
end
function cmd = xpdf_command(path_)
% Initialize any required system calls before calling ghostscript
% TODO: in Unix/Mac, find a way to determine whether to use "export" (bash) or "setenv" (csh/tcsh)
shell_cmd = '';
if isunix
% Avoids an error on Linux with outdated MATLAB lib files
% R20XXa/bin/glnxa64/libtiff.so.X
% R20XXa/sys/os/glnxa64/libstdc++.so.X
shell_cmd = 'export LD_LIBRARY_PATH=""; ';
end
if ismac
shell_cmd = 'export DYLD_LIBRARY_PATH=""; ';
end
% Construct the command string
cmd = sprintf('%s"%s" ', shell_cmd, path_);
end
|
github
|
Abakumov/MLIB-master
|
crop_borders.m
|
.m
|
MLIB-master/OTHER/Export_fig/crop_borders.m
| 5,133 |
utf_8
|
b744bf935914cfa6d9ff82140b48291e
|
function [A, vA, vB, bb_rel] = crop_borders(A, bcol, padding, crop_amounts)
%CROP_BORDERS Crop the borders of an image or stack of images
%
% [B, vA, vB, bb_rel] = crop_borders(A, bcol, [padding])
%
%IN:
% A - HxWxCxN stack of images.
% bcol - Cx1 background colour vector.
% padding - scalar indicating how much padding to have in relation to
% the cropped-image-size (0<=padding<=1). Default: 0
% crop_amounts - 4-element vector of crop amounts: [top,right,bottom,left]
% where NaN/Inf indicate auto-cropping, 0 means no cropping,
% and any other value mean cropping in pixel amounts.
%
%OUT:
% B - JxKxCxN cropped stack of images.
% vA - coordinates in A that contain the cropped image
% vB - coordinates in B where the cropped version of A is placed
% bb_rel - relative bounding box (used for eps-cropping)
%{
% 06/03/15: Improved image cropping thanks to Oscar Hartogensis
% 08/06/15: Fixed issue #76: case of transparent figure bgcolor
% 21/02/16: Enabled specifying non-automated crop amounts
% 04/04/16: Fix per Luiz Carvalho for old Matlab releases
% 23/10/16: Fixed issue #175: there used to be a 1px minimal padding in case of crop, now removed
%}
if nargin < 3
padding = 0;
end
if nargin < 4
crop_amounts = nan(1,4); % =auto-cropping
end
crop_amounts(end+1:4) = NaN; % fill missing values with NaN
[h, w, c, n] = size(A);
if isempty(bcol) % case of transparent bgcolor
bcol = A(ceil(end/2),1,:,1);
end
if isscalar(bcol)
bcol = bcol(ones(c, 1));
end
% Crop margin from left
if ~isfinite(crop_amounts(4))
bail = false;
for l = 1:w
for a = 1:c
if ~all(col(A(:,l,a,:)) == bcol(a))
bail = true;
break;
end
end
if bail
break;
end
end
else
l = 1 + abs(crop_amounts(4));
end
% Crop margin from right
if ~isfinite(crop_amounts(2))
bcol = A(ceil(end/2),w,:,1);
bail = false;
for r = w:-1:l
for a = 1:c
if ~all(col(A(:,r,a,:)) == bcol(a))
bail = true;
break;
end
end
if bail
break;
end
end
else
r = w - abs(crop_amounts(2));
end
% Crop margin from top
if ~isfinite(crop_amounts(1))
bcol = A(1,ceil(end/2),:,1);
bail = false;
for t = 1:h
for a = 1:c
if ~all(col(A(t,:,a,:)) == bcol(a))
bail = true;
break;
end
end
if bail
break;
end
end
else
t = 1 + abs(crop_amounts(1));
end
% Crop margin from bottom
bcol = A(h,ceil(end/2),:,1);
if ~isfinite(crop_amounts(3))
bail = false;
for b = h:-1:t
for a = 1:c
if ~all(col(A(b,:,a,:)) == bcol(a))
bail = true;
break;
end
end
if bail
break;
end
end
else
b = h - abs(crop_amounts(3));
end
if padding == 0 % no padding
% Issue #175: there used to be a 1px minimal padding in case of crop, now removed
%{
if ~isequal([t b l r], [1 h 1 w]) % Check if we're actually croppping
padding = 1; % Leave one boundary pixel to avoid bleeding on resize
bcol(:) = nan; % make the 1px padding transparent
end
%}
elseif abs(padding) < 1 % pad value is a relative fraction of image size
padding = sign(padding)*round(mean([b-t r-l])*abs(padding)); % ADJUST PADDING
else % pad value is in units of 1/72" points
padding = round(padding); % fix cases of non-integer pad value
end
if padding > 0 % extra padding
% Create an empty image, containing the background color, that has the
% cropped image size plus the padded border
B = repmat(bcol,[(b-t)+1+padding*2,(r-l)+1+padding*2,1,n]); % Fix per Luiz Carvalho
% vA - coordinates in A that contain the cropped image
vA = [t b l r];
% vB - coordinates in B where the cropped version of A will be placed
vB = [padding+1, (b-t)+1+padding, padding+1, (r-l)+1+padding];
% Place the original image in the empty image
B(vB(1):vB(2), vB(3):vB(4), :, :) = A(vA(1):vA(2), vA(3):vA(4), :, :);
A = B;
else % extra cropping
vA = [t-padding b+padding l-padding r+padding];
A = A(vA(1):vA(2), vA(3):vA(4), :, :);
vB = [NaN NaN NaN NaN];
end
% For EPS cropping, determine the relative BoundingBox - bb_rel
bb_rel = [l-1 h-b-1 r+1 h-t+1]./[w h w h];
end
function A = col(A)
A = A(:);
end
|
github
|
Abakumov/MLIB-master
|
isolate_axes.m
|
.m
|
MLIB-master/OTHER/Export_fig/isolate_axes.m
| 4,851 |
utf_8
|
611d9727e84ad6ba76dcb3543434d0ce
|
function fh = isolate_axes(ah, vis)
%ISOLATE_AXES Isolate the specified axes in a figure on their own
%
% Examples:
% fh = isolate_axes(ah)
% fh = isolate_axes(ah, vis)
%
% This function will create a new figure containing the axes/uipanels
% specified, and also their associated legends and colorbars. The objects
% specified must all be in the same figure, but they will generally only be
% a subset of the objects in the figure.
%
% IN:
% ah - An array of axes and uipanel handles, which must come from the
% same figure.
% vis - A boolean indicating whether the new figure should be visible.
% Default: false.
%
% OUT:
% fh - The handle of the created figure.
% Copyright (C) Oliver Woodford 2011-2013
% Thank you to Rosella Blatt for reporting a bug to do with axes in GUIs
% 16/03/12: Moved copyfig to its own function. Thanks to Bob Fratantonio
% for pointing out that the function is also used in export_fig.m
% 12/12/12: Add support for isolating uipanels. Thanks to michael for suggesting it
% 08/10/13: Bug fix to allchildren suggested by Will Grant (many thanks!)
% 05/12/13: Bug fix to axes having different units. Thanks to Remington Reid for reporting
% 21/04/15: Bug fix for exporting uipanels with legend/colorbar on HG1 (reported by Alvaro
% on FEX page as a comment on 24-Apr-2014); standardized indentation & help section
% 22/04/15: Bug fix: legends and colorbars were not exported when exporting axes handle in HG2
% Make sure we have an array of handles
if ~all(ishandle(ah))
error('ah must be an array of handles');
end
% Check that the handles are all for axes or uipanels, and are all in the same figure
fh = ancestor(ah(1), 'figure');
nAx = numel(ah);
for a = 1:nAx
if ~ismember(get(ah(a), 'Type'), {'axes', 'uipanel'})
error('All handles must be axes or uipanel handles.');
end
if ~isequal(ancestor(ah(a), 'figure'), fh)
error('Axes must all come from the same figure.');
end
end
% Tag the objects so we can find them in the copy
old_tag = get(ah, 'Tag');
if nAx == 1
old_tag = {old_tag};
end
set(ah, 'Tag', 'ObjectToCopy');
% Create a new figure exactly the same as the old one
fh = copyfig(fh); %copyobj(fh, 0);
if nargin < 2 || ~vis
set(fh, 'Visible', 'off');
end
% Reset the object tags
for a = 1:nAx
set(ah(a), 'Tag', old_tag{a});
end
% Find the objects to save
ah = findall(fh, 'Tag', 'ObjectToCopy');
if numel(ah) ~= nAx
close(fh);
error('Incorrect number of objects found.');
end
% Set the axes tags to what they should be
for a = 1:nAx
set(ah(a), 'Tag', old_tag{a});
end
% Keep any legends and colorbars which overlap the subplots
% Note: in HG1 these are axes objects; in HG2 they are separate objects, therefore we
% don't test for the type, only the tag (hopefully nobody but Matlab uses them!)
lh = findall(fh, 'Tag', 'legend', '-or', 'Tag', 'Colorbar');
nLeg = numel(lh);
if nLeg > 0
set([ah(:); lh(:)], 'Units', 'normalized');
try
ax_pos = get(ah, 'OuterPosition'); % axes and figures have the OuterPosition property
catch
ax_pos = get(ah, 'Position'); % uipanels only have Position, not OuterPosition
end
if nAx > 1
ax_pos = cell2mat(ax_pos(:));
end
ax_pos(:,3:4) = ax_pos(:,3:4) + ax_pos(:,1:2);
try
leg_pos = get(lh, 'OuterPosition');
catch
leg_pos = get(lh, 'Position'); % No OuterPosition in HG2, only in HG1
end
if nLeg > 1;
leg_pos = cell2mat(leg_pos);
end
leg_pos(:,3:4) = leg_pos(:,3:4) + leg_pos(:,1:2);
ax_pos = shiftdim(ax_pos, -1);
% Overlap test
M = bsxfun(@lt, leg_pos(:,1), ax_pos(:,:,3)) & ...
bsxfun(@lt, leg_pos(:,2), ax_pos(:,:,4)) & ...
bsxfun(@gt, leg_pos(:,3), ax_pos(:,:,1)) & ...
bsxfun(@gt, leg_pos(:,4), ax_pos(:,:,2));
ah = [ah; lh(any(M, 2))];
end
% Get all the objects in the figure
axs = findall(fh);
% Delete everything except for the input objects and associated items
delete(axs(~ismember(axs, [ah; allchildren(ah); allancestors(ah)])));
end
function ah = allchildren(ah)
ah = findall(ah);
if iscell(ah)
ah = cell2mat(ah);
end
ah = ah(:);
end
function ph = allancestors(ah)
ph = [];
for a = 1:numel(ah)
h = get(ah(a), 'parent');
while h ~= 0
ph = [ph; h];
h = get(h, 'parent');
end
end
end
|
github
|
Abakumov/MLIB-master
|
im2gif.m
|
.m
|
MLIB-master/OTHER/Export_fig/im2gif.m
| 6,769 |
utf_8
|
92402e010eade0a1789e9e9ae59c6e07
|
%IM2GIF Convert a multiframe image to an animated GIF file
%
% Examples:
% im2gif infile
% im2gif infile outfile
% im2gif(A, outfile)
% im2gif(..., '-nocrop')
% im2gif(..., '-nodither')
% im2gif(..., '-ncolors', n)
% im2gif(..., '-loops', n)
% im2gif(..., '-delay', n)
%
% This function converts a multiframe image to an animated GIF.
%
% To create an animation from a series of figures, export to a multiframe
% TIFF file using export_fig, then convert to a GIF, as follows:
%
% for a = 2 .^ (3:6)
% peaks(a);
% export_fig test.tif -nocrop -append
% end
% im2gif('test.tif', '-delay', 0.5);
%
%IN:
% infile - string containing the name of the input image.
% outfile - string containing the name of the output image (must have the
% .gif extension). Default: infile, with .gif extension.
% A - HxWxCxN array of input images, stacked along fourth dimension, to
% be converted to gif.
% -nocrop - option indicating that the borders of the output are not to
% be cropped.
% -nodither - option indicating that dithering is not to be used when
% converting the image.
% -ncolors - option pair, the value of which indicates the maximum number
% of colors the GIF can have. This can also be a quantization
% tolerance, between 0 and 1. Default/maximum: 256.
% -loops - option pair, the value of which gives the number of times the
% animation is to be looped. Default: 65535.
% -delay - option pair, the value of which gives the time, in seconds,
% between frames. Default: 1/15.
% Copyright (C) Oliver Woodford 2011
%{
% 14/02/18: Merged issue #235: reduced memory usage, improved performance (thanks to @numb7rs)
%}
function im2gif(A, varargin)
% Parse the input arguments
[A, options] = parse_args(A, varargin{:});
if options.crop ~= 0
% Crop
A = crop_borders(A, A(ceil(end/2),1,:,1));
end
% Convert to indexed image
[h, w, c, n] = size(A);
% Issue #235: Using unique(A,'rows') on the whole image stack at once causes
% massive memory usage when dealing with large images (at least on Matlab 2017b).
% Running unique(...) on individual frames, then again on the results drastically
% reduces the memory usage & slightly improves the execution time (@numb7rs).
uns = cell(1,size(A,4));
for nn=1:size(A,4)
uns{nn}=unique(reshape(A(:,:,:,nn), h*w, c),'rows');
end
map=unique(cell2mat(uns'),'rows');
A = reshape(permute(A, [1 2 4 3]), h, w*n, c);
if size(map, 1) > 256
dither_str = {'dither', 'nodither'};
dither_str = dither_str{1+(options.dither==0)};
if options.ncolors <= 1
[B, map] = rgb2ind(A, options.ncolors, dither_str);
if size(map, 1) > 256
[B, map] = rgb2ind(A, 256, dither_str);
end
else
[B, map] = rgb2ind(A, min(round(options.ncolors), 256), dither_str);
end
else
if max(map(:)) > 1
map = double(map) / 255;
A = double(A) / 255;
end
B = rgb2ind(im2double(A), map);
end
B = reshape(B, h, w, 1, n);
% Bug fix to rgb2ind
map(B(1)+1,:) = im2double(A(1,1,:));
% Save as a gif
imwrite(B, map, options.outfile, 'LoopCount', round(options.loops(1)), 'DelayTime', options.delay);
end
%% Parse the input arguments
function [A, options] = parse_args(A, varargin)
% Set the defaults
options = struct('outfile', '', ...
'dither', true, ...
'crop', true, ...
'ncolors', 256, ...
'loops', 65535, ...
'delay', 1/15);
% Go through the arguments
a = 0;
n = numel(varargin);
while a < n
a = a + 1;
if ischar(varargin{a}) && ~isempty(varargin{a})
if varargin{a}(1) == '-'
opt = lower(varargin{a}(2:end));
switch opt
case 'nocrop'
options.crop = false;
case 'nodither'
options.dither = false;
otherwise
if ~isfield(options, opt)
error('Option %s not recognized', varargin{a});
end
a = a + 1;
if ischar(varargin{a}) && ~ischar(options.(opt))
options.(opt) = str2double(varargin{a});
else
options.(opt) = varargin{a};
end
end
else
options.outfile = varargin{a};
end
end
end
if isempty(options.outfile)
if ~ischar(A)
error('No output filename given.');
end
% Generate the output filename from the input filename
[path, outfile] = fileparts(A);
options.outfile = fullfile(path, [outfile '.gif']);
end
if ischar(A)
% Read in the image
A = imread_rgb(A);
end
end
%% Read image to uint8 rgb array
function [A, alpha] = imread_rgb(name)
% Get file info
info = imfinfo(name);
% Special case formats
switch lower(info(1).Format)
case 'gif'
[A, map] = imread(name, 'frames', 'all');
if ~isempty(map)
map = uint8(map * 256 - 0.5); % Convert to uint8 for storage
A = reshape(map(uint32(A)+1,:), [size(A) size(map, 2)]); % Assume indexed from 0
A = permute(A, [1 2 5 4 3]);
end
case {'tif', 'tiff'}
A = cell(numel(info), 1);
for a = 1:numel(A)
[A{a}, map] = imread(name, 'Index', a, 'Info', info);
if ~isempty(map)
map = uint8(map * 256 - 0.5); % Convert to uint8 for storage
A{a} = reshape(map(uint32(A{a})+1,:), [size(A) size(map, 2)]); % Assume indexed from 0
end
if size(A{a}, 3) == 4
% TIFF in CMYK colourspace - convert to RGB
if isfloat(A{a})
A{a} = A{a} * 255;
else
A{a} = single(A{a});
end
A{a} = 255 - A{a};
A{a}(:,:,4) = A{a}(:,:,4) / 255;
A{a} = uint8(A(:,:,1:3) .* A{a}(:,:,[4 4 4]));
end
end
A = cat(4, A{:});
otherwise
[A, map, alpha] = imread(name);
A = A(:,:,:,1); % Keep only first frame of multi-frame files
if ~isempty(map)
map = uint8(map * 256 - 0.5); % Convert to uint8 for storage
A = reshape(map(uint32(A)+1,:), [size(A) size(map, 2)]); % Assume indexed from 0
elseif size(A, 3) == 4
% Assume 4th channel is an alpha matte
alpha = A(:,:,4);
A = A(:,:,1:3);
end
end
end
|
github
|
Abakumov/MLIB-master
|
read_write_entire_textfile.m
|
.m
|
MLIB-master/OTHER/Export_fig/read_write_entire_textfile.m
| 961 |
utf_8
|
775aa1f538c76516c7fb406a4f129320
|
%READ_WRITE_ENTIRE_TEXTFILE Read or write a whole text file to/from memory
%
% Read or write an entire text file to/from memory, without leaving the
% file open if an error occurs.
%
% Reading:
% fstrm = read_write_entire_textfile(fname)
% Writing:
% read_write_entire_textfile(fname, fstrm)
%
%IN:
% fname - Pathname of text file to be read in.
% fstrm - String to be written to the file, including carriage returns.
%
%OUT:
% fstrm - String read from the file. If an fstrm input is given the
% output is the same as that input.
function fstrm = read_write_entire_textfile(fname, fstrm)
modes = {'rt', 'wt'};
writing = nargin > 1;
fh = fopen(fname, modes{1+writing});
if fh == -1
error('Unable to open file %s.', fname);
end
try
if writing
fwrite(fh, fstrm, 'char*1');
else
fstrm = fread(fh, '*char')';
end
catch ex
fclose(fh);
rethrow(ex);
end
fclose(fh);
end
|
github
|
Abakumov/MLIB-master
|
pdf2eps.m
|
.m
|
MLIB-master/OTHER/Export_fig/pdf2eps.m
| 1,522 |
utf_8
|
4c8f0603619234278ed413670d24bdb6
|
%PDF2EPS Convert a pdf file to eps format using pdftops
%
% Examples:
% pdf2eps source dest
%
% This function converts a pdf file to eps format.
%
% This function requires that you have pdftops, from the Xpdf suite of
% functions, installed on your system. This can be downloaded from:
% http://www.foolabs.com/xpdf
%
%IN:
% source - filename of the source pdf file to convert. The filename is
% assumed to already have the extension ".pdf".
% dest - filename of the destination eps file. The filename is assumed to
% already have the extension ".eps".
% Copyright (C) Oliver Woodford 2009-2010
% Thanks to Aldebaro Klautau for reporting a bug when saving to
% non-existant directories.
function pdf2eps(source, dest)
% Construct the options string for pdftops
options = ['-q -paper match -eps -level2 "' source '" "' dest '"'];
% Convert to eps using pdftops
[status, message] = pdftops(options);
% Check for error
if status
% Report error
if isempty(message)
error('Unable to generate eps. Check destination directory is writable.');
else
error(message);
end
end
% Fix the DSC error created by pdftops
fid = fopen(dest, 'r+');
if fid == -1
% Cannot open the file
return
end
fgetl(fid); % Get the first line
str = fgetl(fid); % Get the second line
if strcmp(str(1:min(13, end)), '% Produced by')
fseek(fid, -numel(str)-1, 'cof');
fwrite(fid, '%'); % Turn ' ' into '%'
end
fclose(fid);
end
|
github
|
Abakumov/MLIB-master
|
print2array.m
|
.m
|
MLIB-master/OTHER/Export_fig/print2array.m
| 10,376 |
utf_8
|
a2022c32ae3efa6007a326692227bd39
|
function [A, bcol] = print2array(fig, res, renderer, gs_options)
%PRINT2ARRAY Exports a figure to an image array
%
% Examples:
% A = print2array
% A = print2array(figure_handle)
% A = print2array(figure_handle, resolution)
% A = print2array(figure_handle, resolution, renderer)
% A = print2array(figure_handle, resolution, renderer, gs_options)
% [A bcol] = print2array(...)
%
% This function outputs a bitmap image of the given figure, at the desired
% resolution.
%
% If renderer is '-painters' then ghostcript needs to be installed. This
% can be downloaded from: http://www.ghostscript.com
%
% IN:
% figure_handle - The handle of the figure to be exported. Default: gcf.
% resolution - Resolution of the output, as a factor of screen
% resolution. Default: 1.
% renderer - string containing the renderer paramater to be passed to
% print. Default: '-opengl'.
% gs_options - optional ghostscript options (e.g.: '-dNoOutputFonts'). If
% multiple options are needed, enclose in call array: {'-a','-b'}
%
% OUT:
% A - MxNx3 uint8 image of the figure.
% bcol - 1x3 uint8 vector of the background color
% Copyright (C) Oliver Woodford 2008-2014, Yair Altman 2015-
%{
% 05/09/11: Set EraseModes to normal when using opengl or zbuffer
% renderers. Thanks to Pawel Kocieniewski for reporting the issue.
% 21/09/11: Bug fix: unit8 -> uint8! Thanks to Tobias Lamour for reporting it.
% 14/11/11: Bug fix: stop using hardcopy(), as it interfered with figure size
% and erasemode settings. Makes it a bit slower, but more reliable.
% Thanks to Phil Trinh and Meelis Lootus for reporting the issues.
% 09/12/11: Pass font path to ghostscript.
% 27/01/12: Bug fix affecting painters rendering tall figures. Thanks to
% Ken Campbell for reporting it.
% 03/04/12: Bug fix to median input. Thanks to Andy Matthews for reporting it.
% 26/10/12: Set PaperOrientation to portrait. Thanks to Michael Watts for
% reporting the issue.
% 26/02/15: If temp dir is not writable, use the current folder for temp
% EPS/TIF files (Javier Paredes)
% 27/02/15: Display suggested workarounds to internal print() error (issue #16)
% 28/02/15: Enable users to specify optional ghostscript options (issue #36)
% 10/03/15: Fixed minor warning reported by Paul Soderlind; fixed code indentation
% 28/05/15: Fixed issue #69: patches with LineWidth==0.75 appear wide (internal bug in Matlab's print() func)
% 07/07/15: Fixed issue #83: use numeric handles in HG1
% 11/12/16: Fixed cropping issue reported by Harry D.
%}
% Generate default input arguments, if needed
if nargin < 2
res = 1;
if nargin < 1
fig = gcf;
end
end
% Warn if output is large
old_mode = get(fig, 'Units');
set(fig, 'Units', 'pixels');
px = get(fig, 'Position');
set(fig, 'Units', old_mode);
npx = prod(px(3:4)*res)/1e6;
if npx > 30
% 30M pixels or larger!
warning('MATLAB:LargeImage', 'print2array generating a %.1fM pixel image. This could be slow and might also cause memory problems.', npx);
end
% Retrieve the background colour
bcol = get(fig, 'Color');
% Set the resolution parameter
res_str = ['-r' num2str(ceil(get(0, 'ScreenPixelsPerInch')*res))];
% Generate temporary file name
tmp_nam = [tempname '.tif'];
try
% Ensure that the temp dir is writable (Javier Paredes 26/2/15)
fid = fopen(tmp_nam,'w');
fwrite(fid,1);
fclose(fid);
delete(tmp_nam); % cleanup
isTempDirOk = true;
catch
% Temp dir is not writable, so use the current folder
[dummy,fname,fext] = fileparts(tmp_nam); %#ok<ASGLU>
fpath = pwd;
tmp_nam = fullfile(fpath,[fname fext]);
isTempDirOk = false;
end
% Enable users to specify optional ghostscript options (issue #36)
if nargin > 3 && ~isempty(gs_options)
if iscell(gs_options)
gs_options = sprintf(' %s',gs_options{:});
elseif ~ischar(gs_options)
error('gs_options input argument must be a string or cell-array of strings');
else
gs_options = [' ' gs_options];
end
else
gs_options = '';
end
if nargin > 2 && strcmp(renderer, '-painters')
% First try to print directly to tif file
try
% Print the file into a temporary TIF file and read it into array A
[A, err, ex] = read_tif_img(fig, res_str, renderer, tmp_nam);
if err, rethrow(ex); end
catch % error - try to print to EPS and then using Ghostscript to TIF
% Print to eps file
if isTempDirOk
tmp_eps = [tempname '.eps'];
else
tmp_eps = fullfile(fpath,[fname '.eps']);
end
print2eps(tmp_eps, fig, 0, renderer, '-loose');
try
% Initialize the command to export to tiff using ghostscript
cmd_str = ['-dEPSCrop -q -dNOPAUSE -dBATCH ' res_str ' -sDEVICE=tiff24nc'];
% Set the font path
fp = font_path();
if ~isempty(fp)
cmd_str = [cmd_str ' -sFONTPATH="' fp '"'];
end
% Add the filenames
cmd_str = [cmd_str ' -sOutputFile="' tmp_nam '" "' tmp_eps '"' gs_options];
% Execute the ghostscript command
ghostscript(cmd_str);
catch me
% Delete the intermediate file
delete(tmp_eps);
rethrow(me);
end
% Delete the intermediate file
delete(tmp_eps);
% Read in the generated bitmap
A = imread(tmp_nam);
% Delete the temporary bitmap file
delete(tmp_nam);
end
% Set border pixels to the correct colour
if isequal(bcol, 'none')
bcol = [];
elseif isequal(bcol, [1 1 1])
bcol = uint8([255 255 255]);
else
for l = 1:size(A, 2)
if ~all(reshape(A(:,l,:) == 255, [], 1))
break;
end
end
for r = size(A, 2):-1:l
if ~all(reshape(A(:,r,:) == 255, [], 1))
break;
end
end
for t = 1:size(A, 1)
if ~all(reshape(A(t,:,:) == 255, [], 1))
break;
end
end
for b = size(A, 1):-1:t
if ~all(reshape(A(b,:,:) == 255, [], 1))
break;
end
end
bcol = uint8(median(single([reshape(A(:,[l r],:), [], size(A, 3)); reshape(A([t b],:,:), [], size(A, 3))]), 1));
for c = 1:size(A, 3)
A(:,[1:l-1, r+1:end],c) = bcol(c);
A([1:t-1, b+1:end],:,c) = bcol(c);
end
end
else
if nargin < 3
renderer = '-opengl';
end
% Print the file into a temporary TIF file and read it into array A
[A, err, ex] = read_tif_img(fig, res_str, renderer, tmp_nam);
% Throw any error that occurred
if err
% Display suggested workarounds to internal print() error (issue #16)
fprintf(2, 'An error occured with Matlab''s builtin print function.\nTry setting the figure Renderer to ''painters'' or use opengl(''software'').\n\n');
rethrow(ex);
end
% Set the background color
if isequal(bcol, 'none')
bcol = [];
else
bcol = bcol * 255;
if isequal(bcol, round(bcol))
bcol = uint8(bcol);
else
bcol = squeeze(A(1,1,:));
end
end
end
% Check the output size is correct
if isequal(res, round(res))
px = round([px([4 3])*res 3]); % round() to avoid an indexing warning below
if ~isequal(size(A), px)
% Correct the output size
A = A(1:min(end,px(1)),1:min(end,px(2)),:);
end
end
end
% Function to create a TIF image of the figure and read it into an array
function [A, err, ex] = read_tif_img(fig, res_str, renderer, tmp_nam)
err = false;
ex = [];
% Temporarily set the paper size
old_pos_mode = get(fig, 'PaperPositionMode');
old_orientation = get(fig, 'PaperOrientation');
set(fig, 'PaperPositionMode','auto', 'PaperOrientation','portrait');
try
% Workaround for issue #69: patches with LineWidth==0.75 appear wide (internal bug in Matlab's print() function)
fp = []; % in case we get an error below
fp = findall(fig, 'Type','patch', 'LineWidth',0.75);
set(fp, 'LineWidth',0.5);
% Fix issue #83: use numeric handles in HG1
if ~using_hg2(fig), fig = double(fig); end
% Print to tiff file
print(fig, renderer, res_str, '-dtiff', tmp_nam);
% Read in the printed file
A = imread(tmp_nam);
% Delete the temporary file
delete(tmp_nam);
catch ex
err = true;
end
set(fp, 'LineWidth',0.75); % restore original figure appearance
% Reset the paper size
set(fig, 'PaperPositionMode',old_pos_mode, 'PaperOrientation',old_orientation);
end
% Function to return (and create, where necessary) the font path
function fp = font_path()
fp = user_string('gs_font_path');
if ~isempty(fp)
return
end
% Create the path
% Start with the default path
fp = getenv('GS_FONTPATH');
% Add on the typical directories for a given OS
if ispc
if ~isempty(fp)
fp = [fp ';'];
end
fp = [fp getenv('WINDIR') filesep 'Fonts'];
else
if ~isempty(fp)
fp = [fp ':'];
end
fp = [fp '/usr/share/fonts:/usr/local/share/fonts:/usr/share/fonts/X11:/usr/local/share/fonts/X11:/usr/share/fonts/truetype:/usr/local/share/fonts/truetype'];
end
user_string('gs_font_path', fp);
end
|
github
|
Abakumov/MLIB-master
|
append_pdfs.m
|
.m
|
MLIB-master/OTHER/Export_fig/append_pdfs.m
| 4,533 |
utf_8
|
a3791bc3c14293ecf9bf50b8ea394f4b
|
%APPEND_PDFS Appends/concatenates multiple PDF files
%
% Example:
% append_pdfs(output, input1, input2, ...)
% append_pdfs(output, input_list{:})
% append_pdfs test.pdf temp1.pdf temp2.pdf
%
% This function appends multiple PDF files to an existing PDF file, or
% concatenates them into a PDF file if the output file doesn't yet exist.
%
% This function requires that you have ghostscript installed on your
% system. Ghostscript can be downloaded from: http://www.ghostscript.com
%
% IN:
% output - string of output file name (including the extension, .pdf).
% If it exists it is appended to; if not, it is created.
% input1 - string of an input file name (including the extension, .pdf).
% All input files are appended in order.
% input_list - cell array list of input file name strings. All input
% files are appended in order.
% Copyright: Oliver Woodford, 2011
% Thanks to Reinhard Knoll for pointing out that appending multiple pdfs in
% one go is much faster than appending them one at a time.
% Thanks to Michael Teo for reporting the issue of a too long command line.
% Issue resolved on 5/5/2011, by passing gs a command file.
% Thanks to Martin Wittmann for pointing out the quality issue when
% appending multiple bitmaps.
% Issue resolved (to best of my ability) 1/6/2011, using the prepress
% setting
% 26/02/15: If temp dir is not writable, use the output folder for temp
% files when appending (Javier Paredes); sanity check of inputs
% 24/01/18: Fixed error in case of existing output file (append mode)
% 24/01/18: Fixed issue #213: non-ASCII characters in folder names on Windows
function append_pdfs(varargin)
if nargin < 2, return; end % sanity check
% Are we appending or creating a new file
append = exist(varargin{1}, 'file') == 2;
output = [tempname '.pdf'];
try
% Ensure that the temp dir is writable (Javier Paredes 26/2/15)
fid = fopen(output,'w');
fwrite(fid,1);
fclose(fid);
delete(output);
isTempDirOk = true;
catch
% Temp dir is not writable, so use the output folder
[dummy,fname,fext] = fileparts(output); %#ok<ASGLU>
fpath = fileparts(varargin{1});
output = fullfile(fpath,[fname fext]);
isTempDirOk = false;
end
if ~append
output = varargin{1};
varargin = varargin(2:end);
end
% Create the command file
if isTempDirOk
cmdfile = [tempname '.txt'];
else
cmdfile = fullfile(fpath,[fname '.txt']);
end
prepareCmdFile(cmdfile, output, varargin{:});
% Call ghostscript
[status, errMsg] = ghostscript(['@"' cmdfile '"']);
% Check for ghostscript execution errors
if status && ~isempty(strfind(errMsg,'undefinedfile')) && ispc
% Fix issue #213: non-ASCII characters in folder names on Windows
for fileIdx = 2 : numel(varargin)
[fpath,fname,fext] = fileparts(varargin{fileIdx});
varargin{fileIdx} = fullfile(normalizePath(fpath),[fname fext]);
end
% Rerun ghostscript with the normalized folder names
prepareCmdFile(cmdfile, output, varargin{:});
[status, errMsg] = ghostscript(['@"' cmdfile '"']);
end
% Delete the command file
delete(cmdfile);
% Check for ghostscript execution errors
if status
error('YMA:export_fig:append_pdf',errMsg);
end
% Rename the file if needed
if append
movefile(output, varargin{1}, 'f');
end
end
% Prepare a text file with ghostscript directives
function prepareCmdFile(cmdfile, output, varargin)
fh = fopen(cmdfile, 'w');
fprintf(fh, '-q -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -dPDFSETTINGS=/prepress -sOutputFile="%s" -f', output);
fprintf(fh, ' "%s"', varargin{:});
fclose(fh);
end
% Convert long/non-ASCII folder names into their short ASCII equivalents
function pathStr = normalizePath(pathStr)
[fpath,fname,fext] = fileparts(pathStr);
if isempty(fpath) || strcmpi(fpath,pathStr), return, end
dirOutput = evalc(['system(''dir /X /AD "' pathStr '*"'')']);
shortName = strtrim(regexprep(dirOutput,{'.*> *',[fname fext '.*']},''));
if isempty(shortName)
shortName = [fname fext];
end
fpath = normalizePath(fpath); %recursive until entire fpath is processed
pathStr = fullfile(fpath, shortName);
end
|
github
|
Abakumov/MLIB-master
|
using_hg2.m
|
.m
|
MLIB-master/OTHER/Export_fig/using_hg2.m
| 1,100 |
utf_8
|
47ca10d86740c27b9f6b397373ae16cd
|
%USING_HG2 Determine if the HG2 graphics engine is used
%
% tf = using_hg2(fig)
%
%IN:
% fig - handle to the figure in question.
%
%OUT:
% tf - boolean indicating whether the HG2 graphics engine is being used
% (true) or not (false).
% 19/06/2015 - Suppress warning in R2015b; cache result for improved performance
% 06/06/2016 - Fixed issue #156 (bad return value in R2016b)
function tf = using_hg2(fig)
persistent tf_cached
if isempty(tf_cached)
try
if nargin < 1, fig = figure('visible','off'); end
oldWarn = warning('off','MATLAB:graphicsversion:GraphicsVersionRemoval');
try
% This generates a [supressed] warning in R2015b:
tf = ~graphicsversion(fig, 'handlegraphics');
catch
tf = ~verLessThan('matlab','8.4'); % =R2014b
end
warning(oldWarn);
catch
tf = false;
end
if nargin < 1, delete(fig); end
tf_cached = tf;
else
tf = tf_cached;
end
end
|
github
|
Abakumov/MLIB-master
|
eps2pdf.m
|
.m
|
MLIB-master/OTHER/Export_fig/eps2pdf.m
| 9,558 |
utf_8
|
9630315aa85db719849672f6f727b68c
|
function eps2pdf(source, dest, crop, append, gray, quality, gs_options)
%EPS2PDF Convert an eps file to pdf format using ghostscript
%
% Examples:
% eps2pdf source dest
% eps2pdf(source, dest, crop)
% eps2pdf(source, dest, crop, append)
% eps2pdf(source, dest, crop, append, gray)
% eps2pdf(source, dest, crop, append, gray, quality)
% eps2pdf(source, dest, crop, append, gray, quality, gs_options)
%
% This function converts an eps file to pdf format. The output can be
% optionally cropped and also converted to grayscale. If the output pdf
% file already exists then the eps file can optionally be appended as a new
% page on the end of the eps file. The level of bitmap compression can also
% optionally be set.
%
% This function requires that you have ghostscript installed on your
% system. Ghostscript can be downloaded from: http://www.ghostscript.com
%
% Inputs:
% source - filename of the source eps file to convert. The filename is
% assumed to already have the extension ".eps".
% dest - filename of the destination pdf file. The filename is assumed
% to already have the extension ".pdf".
% crop - boolean indicating whether to crop the borders off the pdf.
% Default: true.
% append - boolean indicating whether the eps should be appended to the
% end of the pdf as a new page (if the pdf exists already).
% Default: false.
% gray - boolean indicating whether the output pdf should be grayscale
% or not. Default: false.
% quality - scalar indicating the level of image bitmap quality to
% output. A larger value gives a higher quality. quality > 100
% gives lossless output. Default: ghostscript prepress default.
% gs_options - optional ghostscript options (e.g.: '-dNoOutputFonts'). If
% multiple options are needed, enclose in call array: {'-a','-b'}
% Copyright (C) Oliver Woodford 2009-2014, Yair Altman 2015-
% Suggestion of appending pdf files provided by Matt C at:
% http://www.mathworks.com/matlabcentral/fileexchange/23629
% Thank you to Fabio Viola for pointing out compression artifacts, leading
% to the quality setting.
% Thank you to Scott for pointing out the subsampling of very small images,
% which was fixed for lossless compression settings.
% 09/12/11: Pass font path to ghostscript
% 26/02/15: If temp dir is not writable, use the dest folder for temp
% destination files (Javier Paredes)
% 28/02/15: Enable users to specify optional ghostscript options (issue #36)
% 01/03/15: Upon GS error, retry without the -sFONTPATH= option (this might solve
% some /findfont errors according to James Rankin, FEX Comment 23/01/15)
% 23/06/15: Added extra debug info in case of ghostscript error; code indentation
% 04/10/15: Suggest a workaround for issue #41 (missing font path; thanks Mariia Fedotenkova)
% 22/02/16: Bug fix from latest release of this file (workaround for issue #41)
% 20/03/17: Added informational message in case of GS croak (issue #186)
% 16/01/18: Improved appending of multiple EPS files into single PDF (issue #233; thanks @shartjen)
% Intialise the options string for ghostscript
options = ['-q -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -dPDFSETTINGS=/prepress -sOutputFile="' dest '"'];
% Set crop option
if nargin < 3 || crop
options = [options ' -dEPSCrop'];
end
% Set the font path
fp = font_path();
if ~isempty(fp)
options = [options ' -sFONTPATH="' fp '"'];
end
% Set the grayscale option
if nargin > 4 && gray
options = [options ' -sColorConversionStrategy=Gray -dProcessColorModel=/DeviceGray'];
end
% Set the bitmap quality
if nargin > 5 && ~isempty(quality)
options = [options ' -dAutoFilterColorImages=false -dAutoFilterGrayImages=false'];
if quality > 100
options = [options ' -dColorImageFilter=/FlateEncode -dGrayImageFilter=/FlateEncode -c ".setpdfwrite << /ColorImageDownsampleThreshold 10 /GrayImageDownsampleThreshold 10 >> setdistillerparams"'];
else
options = [options ' -dColorImageFilter=/DCTEncode -dGrayImageFilter=/DCTEncode'];
v = 1 + (quality < 80);
quality = 1 - quality / 100;
s = sprintf('<< /QFactor %.2f /Blend 1 /HSample [%d 1 1 %d] /VSample [%d 1 1 %d] >>', quality, v, v, v, v);
options = sprintf('%s -c ".setpdfwrite << /ColorImageDict %s /GrayImageDict %s >> setdistillerparams"', options, s, s);
end
end
% Enable users to specify optional ghostscript options (issue #36)
if nargin > 6 && ~isempty(gs_options)
if iscell(gs_options)
gs_options = sprintf(' %s',gs_options{:});
elseif ~ischar(gs_options)
error('gs_options input argument must be a string or cell-array of strings');
else
gs_options = [' ' gs_options];
end
options = [options gs_options];
end
% Check if the output file exists
if nargin > 3 && append && exist(dest, 'file') == 2
% File exists - append current figure to the end
tmp_nam = [tempname '.pdf'];
[fpath,fname,fext] = fileparts(tmp_nam);
try
% Ensure that the temp dir is writable (Javier Paredes 26/2/15)
fid = fopen(tmp_nam,'w');
fwrite(fid,1);
fclose(fid);
delete(tmp_nam);
catch
% Temp dir is not writable, so use the dest folder
fpath = fileparts(dest);
tmp_nam = fullfile(fpath,[fname fext]);
end
% Copy the existing (dest) pdf file to temporary folder
copyfile(dest, tmp_nam);
% Produce an interim pdf of the source eps, rather than adding the eps directly (issue #233)
ghostscript([options ' -f "' source '"']);
[~,fname] = fileparts(tempname);
tmp_nam2 = fullfile(fpath,[fname fext]); % ensure using a writable folder (not necessarily tempdir)
copyfile(dest, tmp_nam2);
% Add the existing pdf and interim pdf as inputs to ghostscript
%options = [options ' -f "' tmp_nam '" "' source '"']; % append the source eps to dest pdf
options = [options ' -f "' tmp_nam '" "' tmp_nam2 '"']; % append the interim pdf to dest pdf
try
% Convert to pdf using ghostscript
[status, message] = ghostscript(options);
catch me
% Delete the intermediate files and rethrow the error
delete(tmp_nam);
delete(tmp_nam2);
rethrow(me);
end
% Delete the intermediate (temporary) files
delete(tmp_nam);
delete(tmp_nam2);
else
% File doesn't exist or should be over-written
% Add the source eps file as input to ghostscript
options = [options ' -f "' source '"'];
% Convert to pdf using ghostscript
[status, message] = ghostscript(options);
end
% Check for error
if status
% Retry without the -sFONTPATH= option (this might solve some GS
% /findfont errors according to James Rankin, FEX Comment 23/01/15)
orig_options = options;
if ~isempty(fp)
options = regexprep(options, ' -sFONTPATH=[^ ]+ ',' ');
status = ghostscript(options);
if ~status, return; end % hurray! (no error)
end
% Report error
if isempty(message)
error('Unable to generate pdf. Check destination directory is writable.');
elseif ~isempty(strfind(message,'/typecheck in /findfont'))
% Suggest a workaround for issue #41 (missing font path)
font_name = strtrim(regexprep(message,'.*Operand stack:\s*(.*)\s*Execution.*','$1'));
fprintf(2, 'Ghostscript error: could not find the following font(s): %s\n', font_name);
fpath = fileparts(mfilename('fullpath'));
gs_fonts_file = fullfile(fpath, '.ignore', 'gs_font_path.txt');
fprintf(2, ' try to add the font''s folder to your %s file\n\n', gs_fonts_file);
error('export_fig error');
else
fprintf(2, '\nGhostscript error: perhaps %s is open by another application\n', dest);
if ~isempty(gs_options)
fprintf(2, ' or maybe the%s option(s) are not accepted by your GS version\n', gs_options);
end
fprintf(2, ' or maybe you have another gs executable in your system''s path\n');
fprintf(2, 'Ghostscript options: %s\n\n', orig_options);
error(message);
end
end
end
% Function to return (and create, where necessary) the font path
function fp = font_path()
fp = user_string('gs_font_path');
if ~isempty(fp)
return
end
% Create the path
% Start with the default path
fp = getenv('GS_FONTPATH');
% Add on the typical directories for a given OS
if ispc
if ~isempty(fp)
fp = [fp ';'];
end
fp = [fp getenv('WINDIR') filesep 'Fonts'];
else
if ~isempty(fp)
fp = [fp ':'];
end
fp = [fp '/usr/share/fonts:/usr/local/share/fonts:/usr/share/fonts/X11:/usr/local/share/fonts/X11:/usr/share/fonts/truetype:/usr/local/share/fonts/truetype'];
end
user_string('gs_font_path', fp);
end
|
github
|
Abakumov/MLIB-master
|
export_fig.m
|
.m
|
MLIB-master/OTHER/Export_fig/export_fig.m
| 68,032 |
utf_8
|
1c37bb2409b76aca9300742b9bbc60bd
|
function [imageData, alpha] = export_fig(varargin) %#ok<*STRCL1>
%EXPORT_FIG Exports figures in a publication-quality format
%
% Examples:
% imageData = export_fig
% [imageData, alpha] = export_fig
% export_fig filename
% export_fig filename -format1 -format2
% export_fig ... -nocrop
% export_fig ... -c[<val>,<val>,<val>,<val>]
% export_fig ... -transparent
% export_fig ... -native
% export_fig ... -m<val>
% export_fig ... -r<val>
% export_fig ... -a<val>
% export_fig ... -q<val>
% export_fig ... -p<val>
% export_fig ... -d<gs_option>
% export_fig ... -depsc
% export_fig ... -<renderer>
% export_fig ... -<colorspace>
% export_fig ... -append
% export_fig ... -bookmark
% export_fig ... -clipboard
% export_fig ... -update
% export_fig ... -nofontswap
% export_fig ... -font_space <char>
% export_fig ... -linecaps
% export_fig ... -noinvert
% export_fig(..., handle)
%
% This function saves a figure or single axes to one or more vector and/or
% bitmap file formats, and/or outputs a rasterized version to the workspace,
% with the following properties:
% - Figure/axes reproduced as it appears on screen
% - Cropped borders (optional)
% - Embedded fonts (vector formats)
% - Improved line and grid line styles
% - Anti-aliased graphics (bitmap formats)
% - Render images at native resolution (optional for bitmap formats)
% - Transparent background supported (pdf, eps, png, tiff)
% - Semi-transparent patch objects supported (png, tiff)
% - RGB, CMYK or grayscale output (CMYK only with pdf, eps, tiff)
% - Variable image compression, including lossless (pdf, eps, jpg)
% - Optional rounded line-caps (pdf, eps)
% - Optionally append to file (pdf, tiff)
% - Vector formats: pdf, eps
% - Bitmap formats: png, tiff, jpg, bmp, export to workspace
%
% This function is especially suited to exporting figures for use in
% publications and presentations, because of the high quality and
% portability of media produced.
%
% Note that the background color and figure dimensions are reproduced
% (the latter approximately, and ignoring cropping & magnification) in the
% output file. For transparent background (and semi-transparent patch
% objects), use the -transparent option or set the figure 'Color' property
% to 'none'. To make axes transparent set the axes 'Color' property to
% 'none'. PDF, EPS, TIF & PNG are the only formats that support a transparent
% background; only TIF & PNG formats support transparency of patch objects.
%
% The choice of renderer (opengl, zbuffer or painters) has a large impact
% on the quality of output. The default value (opengl for bitmaps, painters
% for vector formats) generally gives good results, but if you aren't
% satisfied then try another renderer. Notes: 1) For vector formats (EPS,
% PDF), only painters generates vector graphics. 2) For bitmaps, only
% opengl can render transparent patch objects correctly. 3) For bitmaps,
% only painters will correctly scale line dash and dot lengths when
% magnifying or anti-aliasing. 4) Fonts may be substitued with Courier when
% using painters.
%
% When exporting to vector format (PDF & EPS) and bitmap format using the
% painters renderer, this function requires that ghostscript is installed
% on your system. You can download this from:
% http://www.ghostscript.com
% When exporting to eps it additionally requires pdftops, from the Xpdf
% suite of functions. You can download this from:
% http://www.foolabs.com/xpdf
%
% Inputs:
% filename - string containing the name (optionally including full or
% relative path) of the file the figure is to be saved as. If
% a path is not specified, the figure is saved in the current
% directory. If no name and no output arguments are specified,
% the default name, 'export_fig_out', is used. If neither a
% file extension nor a format are specified, a ".png" is added
% and the figure saved in that format.
% -format1, -format2, etc. - strings containing the extensions of the
% file formats the figure is to be saved as.
% Valid options are: '-pdf', '-eps', '-png',
% '-tif', '-jpg' and '-bmp'. All combinations
% of formats are valid.
% -nocrop - option indicating that the borders of the output are not to
% be cropped.
% -c[<val>,<val>,<val>,<val>] - option indicating crop amounts. Must be
% a 4-element vector of numeric values: [top,right,bottom,left]
% where NaN/Inf indicate auto-cropping, 0 means no cropping,
% and any other value mean cropping in pixel amounts.
% -transparent - option indicating that the figure background is to be
% made transparent (png, pdf, tif and eps output only).
% -m<val> - option where val indicates the factor to magnify the
% on-screen figure pixel dimensions by when generating bitmap
% outputs (does not affect vector formats). Default: '-m1'.
% -r<val> - option val indicates the resolution (in pixels per inch) to
% export bitmap and vector outputs at, keeping the dimensions
% of the on-screen figure. Default: '-r864' (for vector output
% only). Note that the -m option overides the -r option for
% bitmap outputs only.
% -native - option indicating that the output resolution (when outputting
% a bitmap format) should be such that the vertical resolution
% of the first suitable image found in the figure is at the
% native resolution of that image. To specify a particular
% image to use, give it the tag 'export_fig_native'. Notes:
% This overrides any value set with the -m and -r options. It
% also assumes that the image is displayed front-to-parallel
% with the screen. The output resolution is approximate and
% should not be relied upon. Anti-aliasing can have adverse
% effects on image quality (disable with the -a1 option).
% -a1, -a2, -a3, -a4 - option indicating the amount of anti-aliasing to
% use for bitmap outputs. '-a1' means no anti-
% aliasing; '-a4' is the maximum amount (default).
% -<renderer> - option to force a particular renderer (painters, opengl or
% zbuffer). Default value: opengl for bitmap formats or
% figures with patches and/or transparent annotations;
% painters for vector formats without patches/transparencies.
% -<colorspace> - option indicating which colorspace color figures should
% be saved in: RGB (default), CMYK or gray. CMYK is only
% supported in pdf, eps and tiff output.
% -q<val> - option to vary bitmap image quality (in pdf, eps and jpg
% files only). Larger val, in the range 0-100, gives higher
% quality/lower compression. val > 100 gives lossless
% compression. Default: '-q95' for jpg, ghostscript prepress
% default for pdf & eps. Note: lossless compression can
% sometimes give a smaller file size than the default lossy
% compression, depending on the type of images.
% -p<val> - option to pad a border of width val to exported files, where
% val is either a relative size with respect to cropped image
% size (i.e. p=0.01 adds a 1% border). For EPS & PDF formats,
% val can also be integer in units of 1/72" points (abs(val)>1).
% val can be positive (padding) or negative (extra cropping).
% If used, the -nocrop flag will be ignored, i.e. the image will
% always be cropped and then padded. Default: 0 (i.e. no padding).
% -append - option indicating that if the file (pdfs only) already
% exists, the figure is to be appended as a new page, instead
% of being overwritten (default).
% -bookmark - option to indicate that a bookmark with the name of the
% figure is to be created in the output file (pdf only).
% -clipboard - option to save output as an image on the system clipboard.
% Note: background transparency is not preserved in clipboard
% -d<gs_option> - option to indicate a ghostscript setting. For example,
% -dMaxBitmap=0 or -dNoOutputFonts (Ghostscript 9.15+).
% -depsc - option to use EPS level-3 rather than the default level-2 print
% device. This solves some bugs with Matlab's default -depsc2 device
% such as discolored subplot lines on images (vector formats only).
% -update - option to download and install the latest version of export_fig
% -nofontswap - option to avoid font swapping. Font swapping is automatically
% done in vector formats (only): 11 standard Matlab fonts are
% replaced by the original figure fonts. This option prevents this.
% -font_space <char> - option to set a spacer character for font-names that
% contain spaces, used by EPS/PDF. Default: ''
% -linecaps - option to create rounded line-caps (vector formats only).
% -noinvert - option to avoid setting figure's InvertHardcopy property to
% 'off' during output (this solves some problems of empty outputs).
% handle - The handle of the figure, axes or uipanels (can be an array of
% handles, but the objects must be in the same figure) to be
% saved. Default: gcf.
%
% Outputs:
% imageData - MxNxC uint8 image array of the exported image.
% alpha - MxN single array of alphamatte values in the range [0,1],
% for the case when the background is transparent.
%
% Some helpful examples and tips can be found at:
% https://github.com/altmany/export_fig
%
% See also PRINT, SAVEAS, ScreenCapture (on the Matlab File Exchange)
%{
% Copyright (C) Oliver Woodford 2008-2014, Yair Altman 2015-
% The idea of using ghostscript is inspired by Peder Axensten's SAVEFIG
% (fex id: 10889) which is itself inspired by EPS2PDF (fex id: 5782).
% The idea for using pdftops came from the MATLAB newsgroup (id: 168171).
% The idea of editing the EPS file to change line styles comes from Jiro
% Doke's FIXPSLINESTYLE (fex id: 17928).
% The idea of changing dash length with line width came from comments on
% fex id: 5743, but the implementation is mine :)
% The idea of anti-aliasing bitmaps came from Anders Brun's MYAA (fex id:
% 20979).
% The idea of appending figures in pdfs came from Matt C in comments on the
% FEX (id: 23629)
% Thanks to Roland Martin for pointing out the colour MATLAB
% bug/feature with colorbar axes and transparent backgrounds.
% Thanks also to Andrew Matthews for describing a bug to do with the figure
% size changing in -nodisplay mode. I couldn't reproduce it, but included a
% fix anyway.
% Thanks to Tammy Threadgill for reporting a bug where an axes is not
% isolated from gui objects.
%}
%{
% 23/02/12: Ensure that axes limits don't change during printing
% 14/03/12: Fix bug in fixing the axes limits (thanks to Tobias Lamour for reporting it).
% 02/05/12: Incorporate patch of Petr Nechaev (many thanks), enabling bookmarking of figures in pdf files.
% 09/05/12: Incorporate patch of Arcelia Arrieta (many thanks), to keep tick marks fixed.
% 12/12/12: Add support for isolating uipanels. Thanks to michael for suggesting it.
% 25/09/13: Add support for changing resolution in vector formats. Thanks to Jan Jaap Meijer for suggesting it.
% 07/05/14: Add support for '~' at start of path. Thanks to Sally Warner for suggesting it.
% 24/02/15: Fix Matlab R2014b bug (issue #34): plot markers are not displayed when ZLimMode='manual'
% 25/02/15: Fix issue #4 (using HG2 on R2014a and earlier)
% 25/02/15: Fix issue #21 (bold TeX axes labels/titles in R2014b)
% 26/02/15: If temp dir is not writable, use the user-specified folder for temporary EPS/PDF files (Javier Paredes)
% 27/02/15: Modified repository URL from github.com/ojwoodford to /altmany
% Indented main function
% Added top-level try-catch block to display useful workarounds
% 28/02/15: Enable users to specify optional ghostscript options (issue #36)
% 06/03/15: Improved image padding & cropping thanks to Oscar Hartogensis
% 26/03/15: Fixed issue #49 (bug with transparent grayscale images); fixed out-of-memory issue
% 26/03/15: Fixed issue #42: non-normalized annotations on HG1
% 26/03/15: Fixed issue #46: Ghostscript crash if figure units <> pixels
% 27/03/15: Fixed issue #39: bad export of transparent annotations/patches
% 28/03/15: Fixed issue #50: error on some Matlab versions with the fix for issue #42
% 29/03/15: Fixed issue #33: bugs in Matlab's print() function with -cmyk
% 29/03/15: Improved processing of input args (accept space between param name & value, related to issue #51)
% 30/03/15: When exporting *.fig files, then saveas *.fig if figure is open, otherwise export the specified fig file
% 30/03/15: Fixed edge case bug introduced yesterday (commit #ae1755bd2e11dc4e99b95a7681f6e211b3fa9358)
% 09/04/15: Consolidated header comment sections; initialize output vars only if requested (nargout>0)
% 14/04/15: Workaround for issue #45: lines in image subplots are exported in invalid color
% 15/04/15: Fixed edge-case in parsing input parameters; fixed help section to show the -depsc option (issue #45)
% 21/04/15: Bug fix: Ghostscript croaks on % chars in output PDF file (reported by Sven on FEX page, 15-Jul-2014)
% 22/04/15: Bug fix: Pdftops croaks on relative paths (reported by Tintin Milou on FEX page, 19-Jan-2015)
% 04/05/15: Merged fix #63 (Kevin Mattheus Moerman): prevent tick-label changes during export
% 07/05/15: Partial fix for issue #65: PDF export used painters rather than opengl renderer (thanks Nguyenr)
% 08/05/15: Fixed issue #65: bad PDF append since commit #e9f3cdf 21/04/15 (thanks Robert Nguyen)
% 12/05/15: Fixed issue #67: exponent labels cropped in export, since fix #63 (04/05/15)
% 28/05/15: Fixed issue #69: set non-bold label font only if the string contains symbols (\beta etc.), followup to issue #21
% 29/05/15: Added informative error message in case user requested SVG output (issue #72)
% 09/06/15: Fixed issue #58: -transparent removed anti-aliasing when exporting to PNG
% 19/06/15: Added -update option to download and install the latest version of export_fig
% 07/07/15: Added -nofontswap option to avoid font-swapping in EPS/PDF
% 16/07/15: Fixed problem with anti-aliasing on old Matlab releases
% 11/09/15: Fixed issue #103: magnification must never become negative; also fixed reported error msg in parsing input params
% 26/09/15: Alert if trying to export transparent patches/areas to non-PNG outputs (issue #108)
% 04/10/15: Do not suggest workarounds for certain errors that have already been handled previously
% 01/11/15: Fixed issue #112: use same renderer in print2eps as export_fig (thanks to Jesús Pestana Puerta)
% 10/11/15: Custom GS installation webpage for MacOS. Thanks to Andy Hueni via FEX
% 19/11/15: Fixed clipboard export in R2015b (thanks to Dan K via FEX)
% 21/02/16: Added -c option for indicating specific crop amounts (idea by Cedric Noordam on FEX)
% 08/05/16: Added message about possible error reason when groot.Units~=pixels (issue #149)
% 17/05/16: Fixed case of image YData containing more than 2 elements (issue #151)
% 08/08/16: Enabled exporting transparency to TIF, in addition to PNG/PDF (issue #168)
% 11/12/16: Added alert in case of error creating output PDF/EPS file (issue #179)
% 13/12/16: Minor fix to the commit for issue #179 from 2 days ago
% 22/03/17: Fixed issue #187: only set manual ticks when no exponent is present
% 09/04/17: Added -linecaps option (idea by Baron Finer, issue #192)
% 15/09/17: Fixed issue #205: incorrect tick-labels when Ticks number don't match the TickLabels number
% 15/09/17: Fixed issue #210: initialize alpha map to ones instead of zeros when -transparent is not used
% 18/09/17: Added -font_space option to replace font-name spaces in EPS/PDF (workaround for issue #194)
% 18/09/17: Added -noinvert option to solve some export problems with some graphic cards (workaround for issue #197)
% 08/11/17: Fixed issue #220: exponent is removed in HG1 when TickMode is 'manual' (internal Matlab bug)
% 08/11/17: Fixed issue #221: alert if the requested folder does not exist
% 19/11/17: Workaround for issue #207: alert when trying to use transparent bgcolor with -opengl
% 29/11/17: Workaround for issue #206: warn if exporting PDF/EPS for a figure that contains an image
% 11/12/17: Fixed issue #230: use OpenGL renderer when exported image contains transparency (also see issue #206)
% 30/01/18: Updated SVG message to point to https://github.com/kupiqu/plot2svg and display user-selected filename if available
%}
if nargout
[imageData, alpha] = deal([]);
end
hadError = false;
displaySuggestedWorkarounds = true;
% Ensure the figure is rendered correctly _now_ so that properties like axes limits are up-to-date
drawnow;
pause(0.05); % this solves timing issues with Java Swing's EDT (http://undocumentedmatlab.com/blog/solving-a-matlab-hang-problem)
% Parse the input arguments
fig = get(0, 'CurrentFigure');
[fig, options] = parse_args(nargout, fig, varargin{:});
% Ensure that we have a figure handle
if isequal(fig,-1)
return; % silent bail-out
elseif isempty(fig)
error('No figure found');
end
% Isolate the subplot, if it is one
cls = all(ismember(get(fig, 'Type'), {'axes', 'uipanel'}));
if cls
% Given handles of one or more axes, so isolate them from the rest
fig = isolate_axes(fig);
else
% Check we have a figure
if ~isequal(get(fig, 'Type'), 'figure')
error('Handle must be that of a figure, axes or uipanel');
end
% Get the old InvertHardcopy mode
old_mode = get(fig, 'InvertHardcopy');
end
% Hack the font units where necessary (due to a font rendering bug in print?).
% This may not work perfectly in all cases.
% Also it can change the figure layout if reverted, so use a copy.
magnify = options.magnify * options.aa_factor;
if isbitmap(options) && magnify ~= 1
fontu = findall(fig, 'FontUnits', 'normalized');
if ~isempty(fontu)
% Some normalized font units found
if ~cls
fig = copyfig(fig);
set(fig, 'Visible', 'off');
fontu = findall(fig, 'FontUnits', 'normalized');
cls = true;
end
set(fontu, 'FontUnits', 'points');
end
end
try
% MATLAB "feature": axes limits and tick marks can change when printing
Hlims = findall(fig, 'Type', 'axes');
if ~cls
% Record the old axes limit and tick modes
Xlims = make_cell(get(Hlims, 'XLimMode'));
Ylims = make_cell(get(Hlims, 'YLimMode'));
Zlims = make_cell(get(Hlims, 'ZLimMode'));
Xtick = make_cell(get(Hlims, 'XTickMode'));
Ytick = make_cell(get(Hlims, 'YTickMode'));
Ztick = make_cell(get(Hlims, 'ZTickMode'));
Xlabel = make_cell(get(Hlims, 'XTickLabelMode'));
Ylabel = make_cell(get(Hlims, 'YTickLabelMode'));
Zlabel = make_cell(get(Hlims, 'ZTickLabelMode'));
end
% Set all axes limit and tick modes to manual, so the limits and ticks can't change
% Fix Matlab R2014b bug (issue #34): plot markers are not displayed when ZLimMode='manual'
set(Hlims, 'XLimMode', 'manual', 'YLimMode', 'manual');
set_tick_mode(Hlims, 'X');
set_tick_mode(Hlims, 'Y');
if ~using_hg2(fig)
set(Hlims,'ZLimMode', 'manual');
set_tick_mode(Hlims, 'Z');
end
catch
% ignore - fix issue #4 (using HG2 on R2014a and earlier)
end
% Fix issue #21 (bold TeX axes labels/titles in R2014b when exporting to EPS/PDF)
try
if using_hg2(fig) && isvector(options)
% Set the FontWeight of axes labels/titles to 'normal'
% Fix issue #69: set non-bold font only if the string contains symbols (\beta etc.)
texLabels = findall(fig, 'type','text', 'FontWeight','bold');
symbolIdx = ~cellfun('isempty',strfind({texLabels.String},'\'));
set(texLabels(symbolIdx), 'FontWeight','normal');
end
catch
% ignore
end
% Fix issue #42: non-normalized annotations on HG1 (internal Matlab bug)
annotationHandles = [];
try
if ~using_hg2(fig)
annotationHandles = findall(fig,'Type','hggroup','-and','-property','Units','-and','-not','Units','norm');
try % suggested by Jesús Pestana Puerta (jespestana) 30/9/2015
originalUnits = get(annotationHandles,'Units');
set(annotationHandles,'Units','norm');
catch
end
end
catch
% should never happen, but ignore in any case - issue #50
end
% Fix issue #46: Ghostscript crash if figure units <> pixels
oldFigUnits = get(fig,'Units');
set(fig,'Units','pixels');
% Set to print exactly what is there
if options.invert_hardcopy
set(fig, 'InvertHardcopy', 'off');
end
% Set the renderer
switch options.renderer
case 1
renderer = '-opengl';
case 2
renderer = '-zbuffer';
case 3
renderer = '-painters';
otherwise
renderer = '-opengl'; % Default for bitmaps
end
hImages = findall(fig,'type','image');
% Handle transparent patches
hasTransparency = ~isempty(findall(fig,'-property','FaceAlpha','-and','-not','FaceAlpha',1));
hasPatches = ~isempty(findall(fig,'type','patch'));
if hasTransparency
% Alert if trying to export transparent patches/areas to non-supported outputs (issue #108)
% http://www.mathworks.com/matlabcentral/answers/265265-can-export_fig-or-else-draw-vector-graphics-with-transparent-surfaces
% TODO - use transparency when exporting to PDF by not passing via print2eps
msg = 'export_fig currently supports transparent patches/areas only in PNG output. ';
if options.pdf
warning('export_fig:transparency', '%s\nTo export transparent patches/areas to PDF, use the print command:\n print(gcf, ''-dpdf'', ''%s.pdf'');', msg, options.name);
elseif ~options.png && ~options.tif % issue #168
warning('export_fig:transparency', '%s\nTo export the transparency correctly, try using the ScreenCapture utility on the Matlab File Exchange: http://bit.ly/1QFrBip', msg);
end
elseif ~isempty(hImages)
% Fix for issue #230: use OpenGL renderer when exported image contains transparency
for idx = 1 : numel(hImages)
cdata = get(hImages(idx),'CData');
if any(isnan(cdata(:)))
hasTransparency = true;
break
end
end
end
try
% Do the bitmap formats first
if isbitmap(options)
if abs(options.bb_padding) > 1
displaySuggestedWorkarounds = false;
error('For bitmap output (png,jpg,tif,bmp) the padding value (-p) must be between -1<p<1')
end
% Get the background colour
if options.transparent && (options.png || options.alpha)
% Get out an alpha channel
% MATLAB "feature": black colorbar axes can change to white and vice versa!
hCB = findall(fig, 'Type','axes', 'Tag','Colorbar');
if isempty(hCB)
yCol = [];
xCol = [];
else
yCol = get(hCB, 'YColor');
xCol = get(hCB, 'XColor');
if iscell(yCol)
yCol = cell2mat(yCol);
xCol = cell2mat(xCol);
end
yCol = sum(yCol, 2);
xCol = sum(xCol, 2);
end
% MATLAB "feature": apparently figure size can change when changing
% colour in -nodisplay mode
pos = get(fig, 'Position');
% Set the background colour to black, and set size in case it was
% changed internally
tcol = get(fig, 'Color');
set(fig, 'Color', 'k', 'Position', pos);
% Correct the colorbar axes colours
set(hCB(yCol==0), 'YColor', [0 0 0]);
set(hCB(xCol==0), 'XColor', [0 0 0]);
% The following code might cause out-of-memory errors
try
% Print large version to array
B = print2array(fig, magnify, renderer);
% Downscale the image
B = downsize(single(B), options.aa_factor);
catch
% This is more conservative in memory, but kills transparency (issue #58)
B = single(print2array(fig, magnify/options.aa_factor, renderer));
end
% Set background to white (and set size)
set(fig, 'Color', 'w', 'Position', pos);
% Correct the colorbar axes colours
set(hCB(yCol==3), 'YColor', [1 1 1]);
set(hCB(xCol==3), 'XColor', [1 1 1]);
% The following code might cause out-of-memory errors
try
% Print large version to array
A = print2array(fig, magnify, renderer);
% Downscale the image
A = downsize(single(A), options.aa_factor);
catch
% This is more conservative in memory, but kills transparency (issue #58)
A = single(print2array(fig, magnify/options.aa_factor, renderer));
end
% Set the background colour (and size) back to normal
set(fig, 'Color', tcol, 'Position', pos);
% Compute the alpha map
alpha = round(sum(B - A, 3)) / (255 * 3) + 1;
A = alpha;
A(A==0) = 1;
A = B ./ A(:,:,[1 1 1]);
clear B
% Convert to greyscale
if options.colourspace == 2
A = rgb2grey(A);
end
A = uint8(A);
% Crop the background
if options.crop
%[alpha, v] = crop_borders(alpha, 0, 1, options.crop_amounts);
%A = A(v(1):v(2),v(3):v(4),:);
[alpha, vA, vB] = crop_borders(alpha, 0, options.bb_padding, options.crop_amounts);
if ~any(isnan(vB)) % positive padding
B = repmat(uint8(zeros(1,1,size(A,3))),size(alpha));
B(vB(1):vB(2), vB(3):vB(4), :) = A(vA(1):vA(2), vA(3):vA(4), :); % ADDED BY OH
A = B;
else % negative padding
A = A(vA(1):vA(2), vA(3):vA(4), :);
end
end
if options.png
% Compute the resolution
res = options.magnify * get(0, 'ScreenPixelsPerInch') / 25.4e-3;
% Save the png
imwrite(A, [options.name '.png'], 'Alpha', double(alpha), 'ResolutionUnit', 'meter', 'XResolution', res, 'YResolution', res);
% Clear the png bit
options.png = false;
end
% Return only one channel for greyscale
if isbitmap(options)
A = check_greyscale(A);
end
if options.alpha
% Store the image
imageData = A;
% Clear the alpha bit
options.alpha = false;
end
% Get the non-alpha image
if isbitmap(options)
alph = alpha(:,:,ones(1, size(A, 3)));
A = uint8(single(A) .* alph + 255 * (1 - alph));
clear alph
end
if options.im
% Store the new image
imageData = A;
end
else
% Print large version to array
if options.transparent
% MATLAB "feature": apparently figure size can change when changing
% colour in -nodisplay mode
pos = get(fig, 'Position');
tcol = get(fig, 'Color');
set(fig, 'Color', 'w', 'Position', pos);
A = print2array(fig, magnify, renderer);
set(fig, 'Color', tcol, 'Position', pos);
tcol = 255;
else
[A, tcol] = print2array(fig, magnify, renderer);
end
% Crop the background
if options.crop
A = crop_borders(A, tcol, options.bb_padding, options.crop_amounts);
end
% Downscale the image
A = downsize(A, options.aa_factor);
if options.colourspace == 2
% Convert to greyscale
A = rgb2grey(A);
else
% Return only one channel for greyscale
A = check_greyscale(A);
end
% Outputs
if options.im
imageData = A;
end
if options.alpha
imageData = A;
alpha = ones(size(A, 1), size(A, 2), 'single');
end
end
% Save the images
if options.png
res = options.magnify * get(0, 'ScreenPixelsPerInch') / 25.4e-3;
imwrite(A, [options.name '.png'], 'ResolutionUnit', 'meter', 'XResolution', res, 'YResolution', res);
end
if options.bmp
imwrite(A, [options.name '.bmp']);
end
% Save jpeg with given quality
if options.jpg
quality = options.quality;
if isempty(quality)
quality = 95;
end
if quality > 100
imwrite(A, [options.name '.jpg'], 'Mode', 'lossless');
else
imwrite(A, [options.name '.jpg'], 'Quality', quality);
end
end
% Save tif images in cmyk if wanted (and possible)
if options.tif
if options.colourspace == 1 && size(A, 3) == 3
A = double(255 - A);
K = min(A, [], 3);
K_ = 255 ./ max(255 - K, 1);
C = (A(:,:,1) - K) .* K_;
M = (A(:,:,2) - K) .* K_;
Y = (A(:,:,3) - K) .* K_;
A = uint8(cat(3, C, M, Y, K));
clear C M Y K K_
end
append_mode = {'overwrite', 'append'};
imwrite(A, [options.name '.tif'], 'Resolution', options.magnify*get(0, 'ScreenPixelsPerInch'), 'WriteMode', append_mode{options.append+1});
end
end
% Now do the vector formats
if isvector(options)
% Set the default renderer to painters
if ~options.renderer
if hasTransparency || hasPatches
% This is *MUCH* slower, but more accurate for patches and transparent annotations (issue #39)
renderer = '-opengl';
else
renderer = '-painters';
end
end
options.rendererStr = renderer; % fix for issue #112
% Generate some filenames
tmp_nam = [tempname '.eps'];
try
% Ensure that the temp dir is writable (Javier Paredes 30/1/15)
fid = fopen(tmp_nam,'w');
fwrite(fid,1);
fclose(fid);
delete(tmp_nam);
isTempDirOk = true;
catch
% Temp dir is not writable, so use the user-specified folder
[dummy,fname,fext] = fileparts(tmp_nam); %#ok<ASGLU>
fpath = fileparts(options.name);
tmp_nam = fullfile(fpath,[fname fext]);
isTempDirOk = false;
end
if isTempDirOk
pdf_nam_tmp = [tempname '.pdf'];
else
pdf_nam_tmp = fullfile(fpath,[fname '.pdf']);
end
if options.pdf
pdf_nam = [options.name '.pdf'];
try copyfile(pdf_nam, pdf_nam_tmp, 'f'); catch, end % fix for issue #65
else
pdf_nam = pdf_nam_tmp;
end
% Generate the options for print
p2eArgs = {renderer, sprintf('-r%d', options.resolution)};
if options.colourspace == 1 % CMYK
% Issue #33: due to internal bugs in Matlab's print() function, we can't use its -cmyk option
%p2eArgs{end+1} = '-cmyk';
end
if ~options.crop
% Issue #56: due to internal bugs in Matlab's print() function, we can't use its internal cropping mechanism,
% therefore we always use '-loose' (in print2eps.m) and do our own cropping (in crop_borders)
%p2eArgs{end+1} = '-loose';
end
if any(strcmpi(varargin,'-depsc'))
% Issue #45: lines in image subplots are exported in invalid color.
% The workaround is to use the -depsc parameter instead of the default -depsc2
p2eArgs{end+1} = '-depsc';
end
try
% Remove background if requested (issue #207)
if options.transparent %&& ~isequal(get(fig, 'Color'), 'none')
if options.renderer == 1 % OpenGL
warning('export_fig:openglTransparentBG', '-opengl sometimes fails to produce transparent backgrounds; try -painters instead');
else
originalBgColor = get(fig, 'Color');
set(fig,'Color','none');
end
end
% Generate an eps
print2eps(tmp_nam, fig, options, p2eArgs{:});
% {
% Remove the background, if desired
if options.transparent %&& ~isequal(get(fig, 'Color'), 'none')
eps_remove_background(tmp_nam, 1 + using_hg2(fig));
end
%}
% Restore the figure's previous background color (if modified)
try set(fig,'Color',originalBgColor); drawnow; catch, end
% Fix colorspace to CMYK, if requested (workaround for issue #33)
if options.colourspace == 1 % CMYK
% Issue #33: due to internal bugs in Matlab's print() function, we can't use its -cmyk option
change_rgb_to_cmyk(tmp_nam);
end
% Add a bookmark to the PDF if desired
if options.bookmark
fig_nam = get(fig, 'Name');
if isempty(fig_nam)
warning('export_fig:EmptyBookmark', 'Bookmark requested for figure with no name. Bookmark will be empty.');
end
add_bookmark(tmp_nam, fig_nam);
end
% Generate a pdf
eps2pdf(tmp_nam, pdf_nam_tmp, 1, options.append, options.colourspace==2, options.quality, options.gs_options);
% Ghostscript croaks on % chars in the output PDF file, so use tempname and then rename the file
try
% Rename the file (except if it is already the same)
% Abbie K's comment on the commit for issue #179 (#commitcomment-20173476)
if ~isequal(pdf_nam_tmp, pdf_nam)
movefile(pdf_nam_tmp, pdf_nam, 'f');
end
catch
% Alert in case of error creating output PDF/EPS file (issue #179)
if exist(pdf_nam_tmp, 'file')
error(['Could not create ' pdf_nam ' - perhaps the folder does not exist, or you do not have write permissions']);
else
error('Could not generate the intermediary EPS file.');
end
end
catch ex
% Delete the eps
delete(tmp_nam);
rethrow(ex);
end
% Delete the eps
delete(tmp_nam);
if options.eps || options.linecaps
try
% Generate an eps from the pdf
% since pdftops can't handle relative paths (e.g., '..\'), use a temp file
eps_nam_tmp = strrep(pdf_nam_tmp,'.pdf','.eps');
pdf2eps(pdf_nam, eps_nam_tmp);
% Issue #192: enable rounded line-caps
if options.linecaps
fstrm = read_write_entire_textfile(eps_nam_tmp);
fstrm = regexprep(fstrm, '[02] J', '1 J');
read_write_entire_textfile(eps_nam_tmp, fstrm);
if options.pdf
eps2pdf(eps_nam_tmp, pdf_nam, 1, options.append, options.colourspace==2, options.quality, options.gs_options);
end
end
if options.eps
movefile(eps_nam_tmp, [options.name '.eps'], 'f');
else % if options.pdf
try delete(eps_nam_tmp); catch, end
end
catch ex
if ~options.pdf
% Delete the pdf
delete(pdf_nam);
end
try delete(eps_nam_tmp); catch, end
rethrow(ex);
end
if ~options.pdf
% Delete the pdf
delete(pdf_nam);
end
end
% Issue #206: warn if the figure contains an image
if ~isempty(hImages) && strcmpi(renderer,'-opengl') % see addendum to issue #206
warnMsg = ['exporting images to PDF/EPS may result in blurry images on some viewers. ' ...
'If so, try to change viewer, or increase the image''s CData resolution, or use -opengl renderer, or export via the print function. ' ...
'See <a href="matlab:web(''https://github.com/altmany/export_fig/issues/206'',''-browser'');">issue #206</a> for details.'];
warning('export_fig:pdf_eps:blurry_image', warnMsg);
end
end
% Revert the figure or close it (if requested)
if cls || options.closeFig
% Close the created figure
close(fig);
else
% Reset the hardcopy mode
set(fig, 'InvertHardcopy', old_mode);
% Reset the axes limit and tick modes
for a = 1:numel(Hlims)
try
set(Hlims(a), 'XLimMode', Xlims{a}, 'YLimMode', Ylims{a}, 'ZLimMode', Zlims{a},...
'XTickMode', Xtick{a}, 'YTickMode', Ytick{a}, 'ZTickMode', Ztick{a},...
'XTickLabelMode', Xlabel{a}, 'YTickLabelMode', Ylabel{a}, 'ZTickLabelMode', Zlabel{a});
catch
% ignore - fix issue #4 (using HG2 on R2014a and earlier)
end
end
% Revert the tex-labels font weights
try set(texLabels, 'FontWeight','bold'); catch, end
% Revert annotation units
for handleIdx = 1 : numel(annotationHandles)
try
oldUnits = originalUnits{handleIdx};
catch
oldUnits = originalUnits;
end
try set(annotationHandles(handleIdx),'Units',oldUnits); catch, end
end
% Revert figure units
set(fig,'Units',oldFigUnits);
end
% Output to clipboard (if requested)
if options.clipboard
% Delete the output file if unchanged from the default name ('export_fig_out.png')
if strcmpi(options.name,'export_fig_out')
try
fileInfo = dir('export_fig_out.png');
if ~isempty(fileInfo)
timediff = now - fileInfo.datenum;
ONE_SEC = 1/24/60/60;
if timediff < ONE_SEC
delete('export_fig_out.png');
end
end
catch
% never mind...
end
end
% Save the image in the system clipboard
% credit: Jiro Doke's IMCLIPBOARD: http://www.mathworks.com/matlabcentral/fileexchange/28708-imclipboard
try
error(javachk('awt', 'export_fig -clipboard output'));
catch
warning('export_fig:clipboardJava', 'export_fig -clipboard output failed: requires Java to work');
return;
end
try
% Import necessary Java classes
import java.awt.Toolkit
import java.awt.image.BufferedImage
import java.awt.datatransfer.DataFlavor
% Get System Clipboard object (java.awt.Toolkit)
cb = Toolkit.getDefaultToolkit.getSystemClipboard();
% Add java class (ImageSelection) to the path
if ~exist('ImageSelection', 'class')
javaaddpath(fileparts(which(mfilename)), '-end');
end
% Get image size
ht = size(imageData, 1);
wd = size(imageData, 2);
% Convert to Blue-Green-Red format
try
imageData2 = imageData(:, :, [3 2 1]);
catch
% Probably gray-scaled image (2D, without the 3rd [RGB] dimension)
imageData2 = imageData(:, :, [1 1 1]);
end
% Convert to 3xWxH format
imageData2 = permute(imageData2, [3, 2, 1]);
% Append Alpha data (unused - transparency is not supported in clipboard copy)
alphaData2 = uint8(permute(255*alpha,[3,2,1])); %=255*ones(1,wd,ht,'uint8')
imageData2 = cat(1, imageData2, alphaData2);
% Create image buffer
imBuffer = BufferedImage(wd, ht, BufferedImage.TYPE_INT_RGB);
imBuffer.setRGB(0, 0, wd, ht, typecast(imageData2(:), 'int32'), 0, wd);
% Create ImageSelection object from the image buffer
imSelection = ImageSelection(imBuffer);
% Set clipboard content to the image
cb.setContents(imSelection, []);
catch
warning('export_fig:clipboardFailed', 'export_fig -clipboard output failed: %s', lasterr); %#ok<LERR>
end
end
% Don't output the data to console unless requested
if ~nargout
clear imageData alpha
end
catch err
% Display possible workarounds before the error message
if displaySuggestedWorkarounds && ~strcmpi(err.message,'export_fig error')
if ~hadError, fprintf(2, 'export_fig error. '); end
fprintf(2, 'Please ensure:\n');
fprintf(2, ' that you are using the <a href="https://github.com/altmany/export_fig/archive/master.zip">latest version</a> of export_fig\n');
if ismac
fprintf(2, ' and that you have <a href="http://pages.uoregon.edu/koch">Ghostscript</a> installed\n');
else
fprintf(2, ' and that you have <a href="http://www.ghostscript.com">Ghostscript</a> installed\n');
end
try
if options.eps
fprintf(2, ' and that you have <a href="http://www.foolabs.com/xpdf">pdftops</a> installed\n');
end
catch
% ignore - probably an error in parse_args
end
fprintf(2, ' and that you do not have <a href="matlab:which export_fig -all">multiple versions</a> of export_fig installed by mistake\n');
fprintf(2, ' and that you did not made a mistake in the <a href="matlab:help export_fig">expected input arguments</a>\n');
try
% Alert per issue #149
if ~strncmpi(get(0,'Units'),'pixel',5)
fprintf(2, ' or try to set groot''s Units property back to its default value of ''pixels'' (<a href="matlab:web(''https://github.com/altmany/export_fig/issues/149'',''-browser'');">details</a>)\n');
end
catch
% ignore - maybe an old MAtlab release
end
fprintf(2, '\nIf the problem persists, then please <a href="https://github.com/altmany/export_fig/issues">report a new issue</a>.\n\n');
end
rethrow(err)
end
end
function options = default_options()
% Default options used by export_fig
options = struct(...
'name', 'export_fig_out', ...
'crop', true, ...
'crop_amounts', nan(1,4), ... % auto-crop all 4 image sides
'transparent', false, ...
'renderer', 0, ... % 0: default, 1: OpenGL, 2: ZBuffer, 3: Painters
'pdf', false, ...
'eps', false, ...
'png', false, ...
'tif', false, ...
'jpg', false, ...
'bmp', false, ...
'clipboard', false, ...
'colourspace', 0, ... % 0: RGB/gray, 1: CMYK, 2: gray
'append', false, ...
'im', false, ...
'alpha', false, ...
'aa_factor', 0, ...
'bb_padding', 0, ...
'magnify', [], ...
'resolution', [], ...
'bookmark', false, ...
'closeFig', false, ...
'quality', [], ...
'update', false, ...
'fontswap', true, ...
'font_space', '', ...
'linecaps', false, ...
'invert_hardcopy', true, ...
'gs_options', {{}});
end
function [fig, options] = parse_args(nout, fig, varargin)
% Parse the input arguments
% Set the defaults
native = false; % Set resolution to native of an image
options = default_options();
options.im = (nout == 1); % user requested imageData output
options.alpha = (nout == 2); % user requested alpha output
% Go through the other arguments
skipNext = false;
for a = 1:nargin-2
if skipNext
skipNext = false;
continue;
end
if all(ishandle(varargin{a}))
fig = varargin{a};
elseif ischar(varargin{a}) && ~isempty(varargin{a})
if varargin{a}(1) == '-'
switch lower(varargin{a}(2:end))
case 'nocrop'
options.crop = false;
options.crop_amounts = [0,0,0,0];
case {'trans', 'transparent'}
options.transparent = true;
case 'opengl'
options.renderer = 1;
case 'zbuffer'
options.renderer = 2;
case 'painters'
options.renderer = 3;
case 'pdf'
options.pdf = true;
case 'eps'
options.eps = true;
case 'png'
options.png = true;
case {'tif', 'tiff'}
options.tif = true;
case {'jpg', 'jpeg'}
options.jpg = true;
case 'bmp'
options.bmp = true;
case 'rgb'
options.colourspace = 0;
case 'cmyk'
options.colourspace = 1;
case {'gray', 'grey'}
options.colourspace = 2;
case {'a1', 'a2', 'a3', 'a4'}
options.aa_factor = str2double(varargin{a}(3));
case 'append'
options.append = true;
case 'bookmark'
options.bookmark = true;
case 'native'
native = true;
case 'clipboard'
options.clipboard = true;
options.im = true;
options.alpha = true;
case 'svg'
filename = strrep(options.name,'export_fig_out','filename');
msg = ['SVG output is not supported by export_fig. Use one of the following alternatives:\n' ...
' 1. saveas(gcf,''' filename '.svg'')\n' ...
' 2. plot2svg utility: https://github.com/kupiqu/plot2svg\n' ... % Note: replaced defunct https://github.com/jschwizer99/plot2svg with up-to-date fork on https://github.com/kupiqu/plot2svg
' 3. export_fig to EPS/PDF, then convert to SVG using generic (non-Matlab) tools\n'];
error(sprintf(msg)); %#ok<SPERR>
case 'update'
% Download the latest version of export_fig into the export_fig folder
try
zipFileName = 'https://github.com/altmany/export_fig/archive/master.zip';
folderName = fileparts(which(mfilename('fullpath')));
targetFileName = fullfile(folderName, datestr(now,'yyyy-mm-dd.zip'));
urlwrite(zipFileName,targetFileName);
catch
error('Could not download %s into %s\n',zipFileName,targetFileName);
end
% Unzip the downloaded zip file in the export_fig folder
try
unzip(targetFileName,folderName);
catch
error('Could not unzip %s\n',targetFileName);
end
case 'nofontswap'
options.fontswap = false;
case 'font_space'
options.font_space = varargin{a+1};
skipNext = true;
case 'linecaps'
options.linecaps = true;
case 'noinvert'
options.invert_hardcopy = false;
otherwise
try
wasError = false;
if strcmpi(varargin{a}(1:2),'-d')
varargin{a}(2) = 'd'; % ensure lowercase 'd'
options.gs_options{end+1} = varargin{a};
elseif strcmpi(varargin{a}(1:2),'-c')
if numel(varargin{a})==2
skipNext = true;
vals = str2num(varargin{a+1}); %#ok<ST2NM>
else
vals = str2num(varargin{a}(3:end)); %#ok<ST2NM>
end
if numel(vals)~=4
wasError = true;
error('option -c cannot be parsed: must be a 4-element numeric vector');
end
options.crop_amounts = vals;
options.crop = true;
else % scalar parameter value
val = str2double(regexp(varargin{a}, '(?<=-(m|M|r|R|q|Q|p|P))-?\d*.?\d+', 'match'));
if isempty(val) || isnan(val)
% Issue #51: improved processing of input args (accept space between param name & value)
val = str2double(varargin{a+1});
if isscalar(val) && ~isnan(val)
skipNext = true;
end
end
if ~isscalar(val) || isnan(val)
wasError = true;
error('option %s is not recognised or cannot be parsed', varargin{a});
end
switch lower(varargin{a}(2))
case 'm'
% Magnification may never be negative
if val <= 0
wasError = true;
error('Bad magnification value: %g (must be positive)', val);
end
options.magnify = val;
case 'r'
options.resolution = val;
case 'q'
options.quality = max(val, 0);
case 'p'
options.bb_padding = val;
end
end
catch err
% We might have reached here by raising an intentional error
if wasError % intentional raise
rethrow(err)
else % unintentional
error(['Unrecognized export_fig input option: ''' varargin{a} '''']);
end
end
end
else
[p, options.name, ext] = fileparts(varargin{a});
if ~isempty(p)
% Issue #221: alert if the requested folder does not exist
if ~exist(p,'dir'), error(['Folder ' p ' does not exist!']); end
options.name = [p filesep options.name];
end
switch lower(ext)
case {'.tif', '.tiff'}
options.tif = true;
case {'.jpg', '.jpeg'}
options.jpg = true;
case '.png'
options.png = true;
case '.bmp'
options.bmp = true;
case '.eps'
options.eps = true;
case '.pdf'
options.pdf = true;
case '.fig'
% If no open figure, then load the specified .fig file and continue
if isempty(fig)
fig = openfig(varargin{a},'invisible');
varargin{a} = fig;
options.closeFig = true;
else
% save the current figure as the specified .fig file and exit
saveas(fig(1),varargin{a});
fig = -1;
return
end
case '.svg'
filename = strrep(options.name,'export_fig_out','filename');
msg = ['SVG output is not supported by export_fig. Use one of the following alternatives:\n' ...
' 1. saveas(gcf,''' filename '.svg'')\n' ...
' 2. plot2svg utility: https://github.com/kupiqu/plot2svg\n' ... % Note: replaced defunct https://github.com/jschwizer99/plot2svg with up-to-date fork on https://github.com/kupiqu/plot2svg
' 3. export_fig to EPS/PDF, then convert to SVG using generic (non-Matlab) tools\n'];
error(sprintf(msg)); %#ok<SPERR>
otherwise
options.name = varargin{a};
end
end
end
end
% Quick bail-out if no figure found
if isempty(fig), return; end
% Do border padding with repsect to a cropped image
if options.bb_padding
options.crop = true;
end
% Set default anti-aliasing now we know the renderer
if options.aa_factor == 0
try isAA = strcmp(get(ancestor(fig, 'figure'), 'GraphicsSmoothing'), 'on'); catch, isAA = false; end
options.aa_factor = 1 + 2 * (~(using_hg2(fig) && isAA) | (options.renderer == 3));
end
% Convert user dir '~' to full path
if numel(options.name) > 2 && options.name(1) == '~' && (options.name(2) == '/' || options.name(2) == '\')
options.name = fullfile(char(java.lang.System.getProperty('user.home')), options.name(2:end));
end
% Compute the magnification and resolution
if isempty(options.magnify)
if isempty(options.resolution)
options.magnify = 1;
options.resolution = 864;
else
options.magnify = options.resolution ./ get(0, 'ScreenPixelsPerInch');
end
elseif isempty(options.resolution)
options.resolution = 864;
end
% Set the default format
if ~isvector(options) && ~isbitmap(options)
options.png = true;
end
% Check whether transparent background is wanted (old way)
if isequal(get(ancestor(fig(1), 'figure'), 'Color'), 'none')
options.transparent = true;
end
% If requested, set the resolution to the native vertical resolution of the
% first suitable image found
if native && isbitmap(options)
% Find a suitable image
list = findall(fig, 'Type','image', 'Tag','export_fig_native');
if isempty(list)
list = findall(fig, 'Type','image', 'Visible','on');
end
for hIm = list(:)'
% Check height is >= 2
height = size(get(hIm, 'CData'), 1);
if height < 2
continue
end
% Account for the image filling only part of the axes, or vice versa
yl = get(hIm, 'YData');
if isscalar(yl)
yl = [yl(1)-0.5 yl(1)+height+0.5];
else
yl = [min(yl), max(yl)]; % fix issue #151 (case of yl containing more than 2 elements)
if ~diff(yl)
continue
end
yl = yl + [-0.5 0.5] * (diff(yl) / (height - 1));
end
hAx = get(hIm, 'Parent');
yl2 = get(hAx, 'YLim');
% Find the pixel height of the axes
oldUnits = get(hAx, 'Units');
set(hAx, 'Units', 'pixels');
pos = get(hAx, 'Position');
set(hAx, 'Units', oldUnits);
if ~pos(4)
continue
end
% Found a suitable image
% Account for stretch-to-fill being disabled
pbar = get(hAx, 'PlotBoxAspectRatio');
pos = min(pos(4), pbar(2)*pos(3)/pbar(1));
% Set the magnification to give native resolution
options.magnify = abs((height * diff(yl2)) / (pos * diff(yl))); % magnification must never be negative: issue #103
break
end
end
end
function A = downsize(A, factor)
% Downsample an image
if factor == 1
% Nothing to do
return
end
try
% Faster, but requires image processing toolbox
A = imresize(A, 1/factor, 'bilinear');
catch
% No image processing toolbox - resize manually
% Lowpass filter - use Gaussian as is separable, so faster
% Compute the 1d Gaussian filter
filt = (-factor-1:factor+1) / (factor * 0.6);
filt = exp(-filt .* filt);
% Normalize the filter
filt = single(filt / sum(filt));
% Filter the image
padding = floor(numel(filt) / 2);
for a = 1:size(A, 3)
A(:,:,a) = conv2(filt, filt', single(A([ones(1, padding) 1:end repmat(end, 1, padding)],[ones(1, padding) 1:end repmat(end, 1, padding)],a)), 'valid');
end
% Subsample
A = A(1+floor(mod(end-1, factor)/2):factor:end,1+floor(mod(end-1, factor)/2):factor:end,:);
end
end
function A = rgb2grey(A)
A = cast(reshape(reshape(single(A), [], 3) * single([0.299; 0.587; 0.114]), size(A, 1), size(A, 2)), class(A)); % #ok<ZEROLIKE>
end
function A = check_greyscale(A)
% Check if the image is greyscale
if size(A, 3) == 3 && ...
all(reshape(A(:,:,1) == A(:,:,2), [], 1)) && ...
all(reshape(A(:,:,2) == A(:,:,3), [], 1))
A = A(:,:,1); % Save only one channel for 8-bit output
end
end
function eps_remove_background(fname, count)
% Remove the background of an eps file
% Open the file
fh = fopen(fname, 'r+');
if fh == -1
error('Not able to open file %s.', fname);
end
% Read the file line by line
while count
% Get the next line
l = fgets(fh);
if isequal(l, -1)
break; % Quit, no rectangle found
end
% Check if the line contains the background rectangle
if isequal(regexp(l, ' *0 +0 +\d+ +\d+ +r[fe] *[\n\r]+', 'start'), 1)
% Set the line to whitespace and quit
l(1:regexp(l, '[\n\r]', 'start', 'once')-1) = ' ';
fseek(fh, -numel(l), 0);
fprintf(fh, l);
% Reduce the count
count = count - 1;
end
end
% Close the file
fclose(fh);
end
function b = isvector(options)
b = options.pdf || options.eps;
end
function b = isbitmap(options)
b = options.png || options.tif || options.jpg || options.bmp || options.im || options.alpha;
end
% Helper function
function A = make_cell(A)
if ~iscell(A)
A = {A};
end
end
function add_bookmark(fname, bookmark_text)
% Adds a bookmark to the temporary EPS file after %%EndPageSetup
% Read in the file
fh = fopen(fname, 'r');
if fh == -1
error('File %s not found.', fname);
end
try
fstrm = fread(fh, '*char')';
catch ex
fclose(fh);
rethrow(ex);
end
fclose(fh);
% Include standard pdfmark prolog to maximize compatibility
fstrm = strrep(fstrm, '%%BeginProlog', sprintf('%%%%BeginProlog\n/pdfmark where {pop} {userdict /pdfmark /cleartomark load put} ifelse'));
% Add page bookmark
fstrm = strrep(fstrm, '%%EndPageSetup', sprintf('%%%%EndPageSetup\n[ /Title (%s) /OUT pdfmark',bookmark_text));
% Write out the updated file
fh = fopen(fname, 'w');
if fh == -1
error('Unable to open %s for writing.', fname);
end
try
fwrite(fh, fstrm, 'char*1');
catch ex
fclose(fh);
rethrow(ex);
end
fclose(fh);
end
function set_tick_mode(Hlims, ax)
% Set the tick mode of linear axes to manual
% Leave log axes alone as these are tricky
M = get(Hlims, [ax 'Scale']);
if ~iscell(M)
M = {M};
end
%idx = cellfun(@(c) strcmp(c, 'linear'), M);
idx = find(strcmp(M,'linear'));
%set(Hlims(idx), [ax 'TickMode'], 'manual'); % issue #187
%set(Hlims(idx), [ax 'TickLabelMode'], 'manual'); % this hides exponent label in HG2!
for idx2 = 1 : numel(idx)
try
% Fix for issue #187 - only set manual ticks when no exponent is present
hAxes = Hlims(idx(idx2));
props = {[ax 'TickMode'],'manual', [ax 'TickLabelMode'],'manual'};
tickVals = get(hAxes,[ax 'Tick']);
tickStrs = get(hAxes,[ax 'TickLabel']);
if isempty(strtrim(hAxes.([ax 'Ruler']).SecondaryLabel.String))
% Fix for issue #205 - only set manual ticks when the Ticks number match the TickLabels number
if numel(tickVals) == numel(tickStrs)
set(hAxes, props{:}); % no exponent and matching ticks, so update both ticks and tick labels to manual
end
end
catch % probably HG1
% Fix for issue #220 - exponent is removed in HG1 when TickMode is 'manual' (internal Matlab bug)
if isequal(tickVals, str2num(tickStrs)') %#ok<ST2NM>
set(hAxes, props{:}); % revert back to old behavior
end
end
end
end
function change_rgb_to_cmyk(fname) % convert RGB => CMYK within an EPS file
% Do post-processing on the eps file
try
% Read the EPS file into memory
fstrm = read_write_entire_textfile(fname);
% Replace all gray-scale colors
fstrm = regexprep(fstrm, '\n([\d.]+) +GC\n', '\n0 0 0 ${num2str(1-str2num($1))} CC\n');
% Replace all RGB colors
fstrm = regexprep(fstrm, '\n[0.]+ +[0.]+ +[0.]+ +RC\n', '\n0 0 0 1 CC\n'); % pure black
fstrm = regexprep(fstrm, '\n([\d.]+) +([\d.]+) +([\d.]+) +RC\n', '\n${sprintf(''%.4g '',[1-[str2num($1),str2num($2),str2num($3)]/max([str2num($1),str2num($2),str2num($3)]),1-max([str2num($1),str2num($2),str2num($3)])])} CC\n');
% Overwrite the file with the modified contents
read_write_entire_textfile(fname, fstrm);
catch
% never mind - leave as is...
end
end
|
github
|
Abakumov/MLIB-master
|
ghostscript.m
|
.m
|
MLIB-master/OTHER/Export_fig/ghostscript.m
| 7,902 |
utf_8
|
ff62a40d651197dbea5d3c39998b3bad
|
function varargout = ghostscript(cmd)
%GHOSTSCRIPT Calls a local GhostScript executable with the input command
%
% Example:
% [status result] = ghostscript(cmd)
%
% Attempts to locate a ghostscript executable, finally asking the user to
% specify the directory ghostcript was installed into. The resulting path
% is stored for future reference.
%
% Once found, the executable is called with the input command string.
%
% This function requires that you have Ghostscript installed on your
% system. You can download this from: http://www.ghostscript.com
%
% IN:
% cmd - Command string to be passed into ghostscript.
%
% OUT:
% status - 0 iff command ran without problem.
% result - Output from ghostscript.
% Copyright: Oliver Woodford, 2009-2015, Yair Altman 2015-
%{
% Thanks to Jonas Dorn for the fix for the title of the uigetdir window on Mac OS.
% Thanks to Nathan Childress for the fix to default location on 64-bit Windows systems.
% 27/04/11 - Find 64-bit Ghostscript on Windows. Thanks to Paul Durack and
% Shaun Kline for pointing out the issue
% 04/05/11 - Thanks to David Chorlian for pointing out an alternative
% location for gs on linux.
% 12/12/12 - Add extra executable name on Windows. Thanks to Ratish
% Punnoose for highlighting the issue.
% 28/06/13 - Fix error using GS 9.07 in Linux. Many thanks to Jannick
% Steinbring for proposing the fix.
% 24/10/13 - Fix error using GS 9.07 in Linux. Many thanks to Johannes
% for the fix.
% 23/01/14 - Add full path to ghostscript.txt in warning. Thanks to Koen
% Vermeer for raising the issue.
% 27/02/15 - If Ghostscript croaks, display suggested workarounds
% 30/03/15 - Improved performance by caching status of GS path check, if ok
% 14/05/15 - Clarified warning message in case GS path could not be saved
% 29/05/15 - Avoid cryptic error in case the ghostscipt path cannot be saved (issue #74)
% 10/11/15 - Custom GS installation webpage for MacOS. Thanks to Andy Hueni via FEX
%}
try
% Call ghostscript
[varargout{1:nargout}] = system([gs_command(gs_path()) cmd]);
catch err
% Display possible workarounds for Ghostscript croaks
url1 = 'https://github.com/altmany/export_fig/issues/12#issuecomment-61467998'; % issue #12
url2 = 'https://github.com/altmany/export_fig/issues/20#issuecomment-63826270'; % issue #20
hg2_str = ''; if using_hg2, hg2_str = ' or Matlab R2014a'; end
fprintf(2, 'Ghostscript error. Rolling back to GS 9.10%s may possibly solve this:\n * <a href="%s">%s</a> ',hg2_str,url1,url1);
if using_hg2
fprintf(2, '(GS 9.10)\n * <a href="%s">%s</a> (R2014a)',url2,url2);
end
fprintf('\n\n');
if ismac || isunix
url3 = 'https://github.com/altmany/export_fig/issues/27'; % issue #27
fprintf(2, 'Alternatively, this may possibly be due to a font path issue:\n * <a href="%s">%s</a>\n\n',url3,url3);
% issue #20
fpath = which(mfilename);
if isempty(fpath), fpath = [mfilename('fullpath') '.m']; end
fprintf(2, 'Alternatively, if you are using csh, modify shell_cmd from "export..." to "setenv ..."\nat the bottom of <a href="matlab:opentoline(''%s'',174)">%s</a>\n\n',fpath,fpath);
end
rethrow(err);
end
end
function path_ = gs_path
% Return a valid path
% Start with the currently set path
path_ = user_string('ghostscript');
% Check the path works
if check_gs_path(path_)
return
end
% Check whether the binary is on the path
if ispc
bin = {'gswin32c.exe', 'gswin64c.exe', 'gs'};
else
bin = {'gs'};
end
for a = 1:numel(bin)
path_ = bin{a};
if check_store_gs_path(path_)
return
end
end
% Search the obvious places
if ispc
default_location = 'C:\Program Files\gs\';
dir_list = dir(default_location);
if isempty(dir_list)
default_location = 'C:\Program Files (x86)\gs\'; % Possible location on 64-bit systems
dir_list = dir(default_location);
end
executable = {'\bin\gswin32c.exe', '\bin\gswin64c.exe'};
ver_num = 0;
% If there are multiple versions, use the newest
for a = 1:numel(dir_list)
ver_num2 = sscanf(dir_list(a).name, 'gs%g');
if ~isempty(ver_num2) && ver_num2 > ver_num
for b = 1:numel(executable)
path2 = [default_location dir_list(a).name executable{b}];
if exist(path2, 'file') == 2
path_ = path2;
ver_num = ver_num2;
end
end
end
end
if check_store_gs_path(path_)
return
end
else
executable = {'/usr/bin/gs', '/usr/local/bin/gs'};
for a = 1:numel(executable)
path_ = executable{a};
if check_store_gs_path(path_)
return
end
end
end
% Ask the user to enter the path
while true
if strncmp(computer, 'MAC', 3) % Is a Mac
% Give separate warning as the uigetdir dialogue box doesn't have a
% title
uiwait(warndlg('Ghostscript not found. Please locate the program.'))
end
base = uigetdir('/', 'Ghostcript not found. Please locate the program.');
if isequal(base, 0)
% User hit cancel or closed window
break;
end
base = [base filesep]; %#ok<AGROW>
bin_dir = {'', ['bin' filesep], ['lib' filesep]};
for a = 1:numel(bin_dir)
for b = 1:numel(bin)
path_ = [base bin_dir{a} bin{b}];
if exist(path_, 'file') == 2
if check_store_gs_path(path_)
return
end
end
end
end
end
if ismac
error('Ghostscript not found. Have you installed it (http://pages.uoregon.edu/koch)?');
else
error('Ghostscript not found. Have you installed it from www.ghostscript.com?');
end
end
function good = check_store_gs_path(path_)
% Check the path is valid
good = check_gs_path(path_);
if ~good
return
end
% Update the current default path to the path found
if ~user_string('ghostscript', path_)
filename = fullfile(fileparts(which('user_string.m')), '.ignore', 'ghostscript.txt');
warning('Path to ghostscript installation could not be saved in %s (perhaps a permissions issue). You can manually create this file and set its contents to %s, to improve performance in future invocations (this warning is safe to ignore).', filename, path_);
return
end
end
function good = check_gs_path(path_)
persistent isOk
if isempty(path_)
isOk = false;
elseif ~isequal(isOk,true)
% Check whether the path is valid
[status, message] = system([gs_command(path_) '-h']); %#ok<ASGLU>
isOk = status == 0;
end
good = isOk;
end
function cmd = gs_command(path_)
% Initialize any required system calls before calling ghostscript
% TODO: in Unix/Mac, find a way to determine whether to use "export" (bash) or "setenv" (csh/tcsh)
shell_cmd = '';
if isunix
shell_cmd = 'export LD_LIBRARY_PATH=""; '; % Avoids an error on Linux with GS 9.07
end
if ismac
shell_cmd = 'export DYLD_LIBRARY_PATH=""; '; % Avoids an error on Mac with GS 9.07
end
% Construct the command string
cmd = sprintf('%s"%s" ', shell_cmd, path_);
end
|
github
|
Abakumov/MLIB-master
|
fix_lines.m
|
.m
|
MLIB-master/OTHER/Export_fig/fix_lines.m
| 6,441 |
utf_8
|
ffda929ebad8144b1e72d528fa5d9460
|
%FIX_LINES Improves the line style of eps files generated by print
%
% Examples:
% fix_lines fname
% fix_lines fname fname2
% fstrm_out = fixlines(fstrm_in)
%
% This function improves the style of lines in eps files generated by
% MATLAB's print function, making them more similar to those seen on
% screen. Grid lines are also changed from a dashed style to a dotted
% style, for greater differentiation from dashed lines.
%
% The function also places embedded fonts after the postscript header, in
% versions of MATLAB which place the fonts first (R2006b and earlier), in
% order to allow programs such as Ghostscript to find the bounding box
% information.
%
%IN:
% fname - Name or path of source eps file.
% fname2 - Name or path of destination eps file. Default: same as fname.
% fstrm_in - File contents of a MATLAB-generated eps file.
%
%OUT:
% fstrm_out - Contents of the eps file with line styles fixed.
% Copyright: (C) Oliver Woodford, 2008-2014
% The idea of editing the EPS file to change line styles comes from Jiro
% Doke's FIXPSLINESTYLE (fex id: 17928)
% The idea of changing dash length with line width came from comments on
% fex id: 5743, but the implementation is mine :)
% Thank you to Sylvain Favrot for bringing the embedded font/bounding box
% interaction in older versions of MATLAB to my attention.
% Thank you to D Ko for bringing an error with eps files with tiff previews
% to my attention.
% Thank you to Laurence K for suggesting the check to see if the file was
% opened.
% 01/03/15: Issue #20: warn users if using this function in HG2 (R2014b+)
% 27/03/15: Fixed out of memory issue with enormous EPS files (generated by print() with OpenGL renderer), related to issue #39
function fstrm = fix_lines(fstrm, fname2)
% Issue #20: warn users if using this function in HG2 (R2014b+)
if using_hg2
warning('export_fig:hg2','The fix_lines function should not be used in this Matlab version.');
end
if nargout == 0 || nargin > 1
if nargin < 2
% Overwrite the input file
fname2 = fstrm;
end
% Read in the file
fstrm = read_write_entire_textfile(fstrm);
end
% Move any embedded fonts after the postscript header
if strcmp(fstrm(1:15), '%!PS-AdobeFont-')
% Find the start and end of the header
ind = regexp(fstrm, '[\n\r]%!PS-Adobe-');
[ind2, ind2] = regexp(fstrm, '[\n\r]%%EndComments[\n\r]+');
% Put the header first
if ~isempty(ind) && ~isempty(ind2) && ind(1) < ind2(1)
fstrm = fstrm([ind(1)+1:ind2(1) 1:ind(1) ind2(1)+1:end]);
end
end
% Make sure all line width commands come before the line style definitions,
% so that dash lengths can be based on the correct widths
% Find all line style sections
ind = [regexp(fstrm, '[\n\r]SO[\n\r]'),... % This needs to be here even though it doesn't have dots/dashes!
regexp(fstrm, '[\n\r]DO[\n\r]'),...
regexp(fstrm, '[\n\r]DA[\n\r]'),...
regexp(fstrm, '[\n\r]DD[\n\r]')];
ind = sort(ind);
% Find line width commands
[ind2, ind3] = regexp(fstrm, '[\n\r]\d* w[\n\r]');
% Go through each line style section and swap with any line width commands
% near by
b = 1;
m = numel(ind);
n = numel(ind2);
for a = 1:m
% Go forwards width commands until we pass the current line style
while b <= n && ind2(b) < ind(a)
b = b + 1;
end
if b > n
% No more width commands
break;
end
% Check we haven't gone past another line style (including SO!)
if a < m && ind2(b) > ind(a+1)
continue;
end
% Are the commands close enough to be confident we can swap them?
if (ind2(b) - ind(a)) > 8
continue;
end
% Move the line style command below the line width command
fstrm(ind(a)+1:ind3(b)) = [fstrm(ind(a)+4:ind3(b)) fstrm(ind(a)+1:ind(a)+3)];
b = b + 1;
end
% Find any grid line definitions and change to GR format
% Find the DO sections again as they may have moved
ind = int32(regexp(fstrm, '[\n\r]DO[\n\r]'));
if ~isempty(ind)
% Find all occurrences of what are believed to be axes and grid lines
ind2 = int32(regexp(fstrm, '[\n\r] *\d* *\d* *mt *\d* *\d* *L[\n\r]'));
if ~isempty(ind2)
% Now see which DO sections come just before axes and grid lines
ind2 = repmat(ind2', [1 numel(ind)]) - repmat(ind, [numel(ind2) 1]);
ind2 = any(ind2 > 0 & ind2 < 12); % 12 chars seems about right
ind = ind(ind2);
% Change any regions we believe to be grid lines to GR
fstrm(ind+1) = 'G';
fstrm(ind+2) = 'R';
end
end
% Define the new styles, including the new GR format
% Dot and dash lengths have two parts: a constant amount plus a line width
% variable amount. The constant amount comes after dpi2point, and the
% variable amount comes after currentlinewidth. If you want to change
% dot/dash lengths for a one particular line style only, edit the numbers
% in the /DO (dotted lines), /DA (dashed lines), /DD (dot dash lines) and
% /GR (grid lines) lines for the style you want to change.
new_style = {'/dom { dpi2point 1 currentlinewidth 0.08 mul add mul mul } bdef',... % Dot length macro based on line width
'/dam { dpi2point 2 currentlinewidth 0.04 mul add mul mul } bdef',... % Dash length macro based on line width
'/SO { [] 0 setdash 0 setlinecap } bdef',... % Solid lines
'/DO { [1 dom 1.2 dom] 0 setdash 0 setlinecap } bdef',... % Dotted lines
'/DA { [4 dam 1.5 dam] 0 setdash 0 setlinecap } bdef',... % Dashed lines
'/DD { [1 dom 1.2 dom 4 dam 1.2 dom] 0 setdash 0 setlinecap } bdef',... % Dot dash lines
'/GR { [0 dpi2point mul 4 dpi2point mul] 0 setdash 1 setlinecap } bdef'}; % Grid lines - dot spacing remains constant
% Construct the output
% This is the original (memory-intensive) code:
%first_sec = strfind(fstrm, '% line types:'); % Isolate line style definition section
%[second_sec, remaining] = strtok(fstrm(first_sec+1:end), '/');
%[remaining, remaining] = strtok(remaining, '%');
%fstrm = [fstrm(1:first_sec) second_sec sprintf('%s\r', new_style{:}) remaining];
fstrm = regexprep(fstrm,'(% line types:.+?)/.+?%',['$1',sprintf('%s\r',new_style{:}),'%']);
% Write the output file
if nargout == 0 || nargin > 1
read_write_entire_textfile(fname2, fstrm);
end
end
|
github
|
Abakumov/MLIB-master
|
WriteSuStructure.m
|
.m
|
MLIB-master/OTHER/SegyMAT/WriteSuStructure.m
| 1,845 |
utf_8
|
3ad8802591e60e4a0ced291ed1d7b543
|
% WriteSuStructure : writes data to disk using SU-CWP format
%
% EX
% WriteSuStructure('datacube.segy',SegyHeader,SegyTraceHeaders,Data);
%
% (C) 2001-2004 Thomas Mejer Hansen, [email protected]/[email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
%
%
function WriteSuStructure(filename,SegyHeader,SegyTraceHeaders,Data)
segyid = fopen(filename,'w'); % USE LOCAL ENDIAN FLAG,
% I.E. ENDIAN FORMAT NOT SPECIFIED
% segyid = fopen(filename,'w','b'); % BIG ENDIAN
% FORCE THE USE OF IEEE
SegyHeader.SegyFormatRevisionNumber=100;
SegyHeader.DataSampleFormat=5; % IEEE
ntraces=size(Data,2);
hw=waitbar(0,['Writing to SU-file : ',filename]);
for i=1:ntraces;
if (i/200)==round(i/200),
SegymatVerbose(['writing trace ',num2str(i),' of ',num2str(ntraces),', filepos=',num2str(ftell(segyid))],1)
SegymatVerbose(SegyTraceHeaders(i).ns,1)
end
PutSegyTrace(segyid,Data(:,i),SegyTraceHeaders(i),SegyHeader);
waitbar(i/ntraces,hw);
end
close(hw)
fclose(segyid);
|
github
|
Abakumov/MLIB-master
|
ReadSegyTrace.m
|
.m
|
MLIB-master/OTHER/SegyMAT/ReadSegyTrace.m
| 1,946 |
utf_8
|
8785e07381ac8f04a5ad72d035b8a746
|
% ReadSegyTrace
function [Data,STH,SegyHeader]=ReadSegyTrace(filename,traces,SegyHeader);
Data=[];
if nargin<3
SegyHeader=GetSegyHeader(filename);
end
if nargin<2
[Data,STH,SegyHeader]=ReadSegyTrace(filename);
end
if (length(traces)>1)
try
Data=zeros(SegyHeader.ns,length(traces));
catch
keyboard
end
for i=1:length(traces)
[Data(:,i),STH(i)]=ReadSegyTrace(filename,traces(i),SegyHeader);
end
return
end
endian='ieee-be'; % Big Endian is default
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% OPEN FILE HANDLE
if exist('endian')==1,
SegymatVerbose([mfilename,' : ENDIAN : ',endian],1)
segyid = fopen(filename,'r',endian);
else
endian='ieee-be';
SegymatVerbose([mfilename,' : ENDIAN SET TO ',endian],0)
segyid = fopen(filename,'r','ieee-be'); % ALL DISK FILES ARE IN BIG
end % ENDIAN FORMAT, ACCORDING TO
Revision=SegyHeader.SegyFormatRevisionNumber;
if Revision>0, Revision=1; end
FormatName=SegyHeader.Rev(Revision+1).DataSampleFormat(SegyHeader.DataSampleFormat).name;
Format=SegyHeader.Rev(Revision+1).DataSampleFormat(SegyHeader.DataSampleFormat).format;
BPS=SegyHeader.Rev(Revision+1).DataSampleFormat(SegyHeader.DataSampleFormat).bps;
txt=['SegyRevision ',sprintf('%0.4g',Revision),', ',FormatName,'(',num2str(SegyHeader.DataSampleFormat),')'];
% move to proper location in segyfile
DataStart=3600+3200*SegyHeader.NumberOfExtTextualHeaders;
fseek(segyid,DataStart,'bof'); % Go to the beginning of the file
skip=240+(BPS/8)*SegyHeader.ns;
fseek(segyid,(traces-1)*skip,'cof');
%SegymatVerbose([num2str(traceinfile),' - SKIPPING TRACE ... ',num2str(outtrace)],2)
TraceStart=ftell(segyid);
STH=GetSegyTraceHeader(segyid,TraceStart,Format,SegyHeader.ns,[]);
Data=GetSegyTraceData(segyid,STH.ns,SegyHeader);
fclose(segyid);
|
github
|
Abakumov/MLIB-master
|
WriteSegyTraceHeaderValue.m
|
.m
|
MLIB-master/OTHER/SegyMAT/WriteSegyTraceHeaderValue.m
| 4,867 |
utf_8
|
a1b22ca5f8710feca8a16d47ace2e64e
|
% WriteSegyTraceHeaderValue : Write trace header valaue at specific location
%
% Call:
%
% % Update all trace header values starting at position 72, in integer32
% % format, to the value 30
% data=30;
% WriteSegyTraceHeaderValue(filename,data,'pos',72,'precision','int32',);
%
% % Update all trace header values starting at position 72, in integer32
% % format, to the values in array 'data'
% ntraces=311;
% data=[1:1:311]*10;
% WriteSegyTraceHeaderValue(filename,data,'pos',72,'precision','int32');
% d_header=ReadSegyTraceHeaderValue(filename,'pos',72,'precision','int32');
%
% % Update the 'cdp' TraceHeader value:
% cdp=ReadSegyTraceHeaderValue(file,'key','cdp'); % READ CDP
% cdp=cdp+10; % change CDP
% WriteSegyTraceHeaderValue(file,cdp,'key','cdp'); % UPDATE CDP
%
% Call 'TraceHeaderDef(1)' to see a list of TraceHeader 'key' names
%
% See also ReadSegyTraceHeaderValue, PutSegyTraceHeader, TraceHeaderDef
%
function dread=WriteSegyTraceHeaderValue(filename,data,varargin);%pos,type)
pos=0;
precision='int32';
ninput=length(varargin);
% TRANSFORM VARARGING INTO PARAMETERS
cargin=1;
while (cargin<ninput)
% ENDIAN FORMAT
endian='ieee-be'; % Big Endian is default
if cargin==5, keyboard; end
if strcmp(varargin{cargin},'endian')
cargin=cargin+1;
eval(['endian_tight=varargin{cargin};'])
if endian_tight=='l',
disp(['USING LITTLE ENDIAN TYPE'])
endian='ieee-le';
else
disp(['USING BIG ENDIAN TYPE'])
end
end
if strcmp(varargin{cargin},'pos')
cargin=cargin+1;
eval(['pos=',num2str(varargin{cargin}),';']);
disp(['Reading at header postision : pos=',num2str(pos)])
end
if strcmp(varargin{cargin},'precision')
cargin=cargin+1;
eval(['precision=''',varargin{cargin},''';']);
disp(['precision : ',precision])
end
if strcmp(varargin{cargin},'key')
cargin=cargin+1;
eval(['key=''',varargin{cargin},''';']);
STH=TraceHeaderDef;
try
pos=STH.(key).pos;
precision=STH.(key).precision;
catch
disp(sprintf('Trace Header Value %s not defined',key))
pos=0; precision='int32';
hval=[];
return
end
disp(sprintf('key=%s, startpos=%d, precision=%s ',key,pos+1,precision))
end
cargin=cargin+1;
end
if exist('endian')==1,
segyid = fopen(filename,'r+',endian);
else
segyid = fopen(filename,'r+','ieee-be'); % ALL DISK FILES ARE IN BIG
end % ENDIAN FORMAT, ACCORDING TO
[SegyHeader]=ReadSegyHeader(filename);
Revision=SegyHeader.SegyFormatRevisionNumber;
if Revision>0, Revision=1; end
if (SegyHeader.DataSampleFormat>length(SegyHeader.Rev(Revision+1).DataSampleFormat));
SegymatVerbose([mfilename,' : WARNING : YOU HAVE SELECTED (OR THE FILE IS FORMATTED SUCH THAT) A DATASAMPLE FORMAT THAT IS NOT DEFINED. \nREMEBER IEEE IS NOT SPECIFIED IN THE SEGY REV0 STANDARD !'])
if (Revision==0)
SegymatVerbose([mfilename,' : TRYING TO USE REVISION 1 AS OPPOSED TO REVISION 0'])
Revision=1;
if (SegyHeader.DataSampleFormat>length(SegyHeader.Rev(Revision+1).DataSampleFormat));
SegymatVerbose([mfilename,' : FATAL ERROR : STILL THE DATASAMPLE FORMAT IS NOT SUPPRTED - EXITING (Report error to [email protected])'])
else
SegymatVerbose([mfilename,' : APPARENT SUCCES CHANING FROM Revision 0 to 1 - Continuing'])
SegyHeader.SegyFormatRevisionNumber=1; % FORCING REVISION TO BE 1 !!!
end
end
end
FormatName=SegyHeader.Rev(Revision+1).DataSampleFormat(SegyHeader.DataSampleFormat).name;
Format=SegyHeader.Rev(Revision+1).DataSampleFormat(SegyHeader.DataSampleFormat).format;
BPS=SegyHeader.Rev(Revision+1).DataSampleFormat(SegyHeader.DataSampleFormat).bps;
txt=['SegyRevision ',sprintf('%0.4g',Revision),', ',FormatName,'(',num2str(SegyHeader.DataSampleFormat),')'];
fseek(segyid,0,'eof'); DataEnd=ftell(segyid);
DataStart=3600+3200*SegyHeader.NumberOfExtTextualHeaders;
fseek(segyid,DataStart,'bof'); % Go to the beginning of the file
ntraces=(DataEnd-DataStart)./(240+(SegyHeader.ns)*(BPS/8));
hval=zeros(1,SegyHeader.ntraces);
for itrace=1:SegyHeader.ntraces
if ((itrace/1000)==round(itrace/1000))
progress_txt(itrace,ntraces,'Trace #')
end
%GOTO START OF TRACE HEADER
skip=DataStart+(itrace-1)*(240+(BPS/8)*SegyHeader.ns);
fseek(segyid,skip,'bof');
fseek(segyid,pos,'cof');
if length(data)==1;
d_trace=data;
else
d_trace=data(itrace);
end
fwrite(segyid,d_trace,precision);
end
if nargout>0
dread=ReadSegyTraceHeaderValue(filename,varargin);
end
fclose(segyid);
|
github
|
Abakumov/MLIB-master
|
SegymatVersion.m
|
.m
|
MLIB-master/OTHER/SegyMAT/SegymatVersion.m
| 1,106 |
utf_8
|
36b4d931ca57c0f119d4e7b587eea364
|
% SegymatVersion - Returns the version and release date
%
% [ver,d]=SegymatVersion;
%
%
% (C) 2001-2011, Thomas Mejer Hansen, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function [ver,d]=SegymatVersion;
version='1.5.1';
releasedate='October 28, 2011';
SegymatVerbose(['This is SegyMAT version ',version,' - released ',releasedate],-1)
ver=version;
d=releasedate;
|
github
|
Abakumov/MLIB-master
|
sac2mat.m
|
.m
|
MLIB-master/OTHER/SegyMAT/sac2mat.m
| 12,807 |
utf_8
|
7160f1bde601678e1eb151228f795428
|
function [SACdata,SeisData,sacfiles]=sac2mat(varargin)
% [SACdata,SeisData,filenames] = SAC2MAT('file1','file2',..., 'filen',endian )
%
% reads n SAC files file1, file2, filen
% and converts them to matlab
% format. The filenames can contain globbing characters (e.g. * and ?).
% These are expanded and all matching files loaded.
%
% files are assumed big endian formatted (e.g. SUN), little endian can be
% forced using endian='l': sac2mat('file1.sac','l');
%
%
% SACSUN2MAT( cellarray ) where cellarray={'file1','file2',...,'filen'}
% is equivalent to the standard form.
%
% SACdata is an n x 1 struct array containing the header variables
% in the same format as is obtained by using MAT function
% of SAC2000.
% SACdata(i).trcLen contains the number of samples.
%
% SeisData is an m x n array (where m=max(npts1, npts2, ...) )
% containing the actual data.
%
% filenames is a n x 1 string cell array with the filenames actually read.
%
% Note that writing
%
% [SACdata,SeisData] = sac2mat('file1','file2',..., 'filen' ,endian)
%
% is equivalent to the following sequence
%
% sac2000
% READ file1 file2 .. filen
% MAT
%
% (in fact the failure of above sequence to work properly on my
% system motivated this script).
%
%
% SAC2MAT was written by F Tilmann ([email protected])
% based on sac_sun2pc_mat by C. D. Saragiotis (I copied the
% routines doing the actual work from this code but
% used a different header structure and made the routine
% flexible).
% It was tested on MATLAB5 on a PC but
% should work on newer versions, too.
%
% (C) 2004
%
% Update 10/2008 by Thomas Mejer Hansen: Merged sac2sun2mat and sacpc2mat
% into sac2mat.m
%
global endian
F = 4-1; % float byte-size minus 1;
K = 8-1; % alphanumeric byte-size minus 1
L = 4-1; % long integer byte-size minus 1;
fnames={};
for i=1:nargin
if ischar(varargin{i})
fnames=cell([fnames; cellstr(varargin{i})]);
elseif iscellstr(varargin{i}) & size(varargin{i},1)==1
fnames=cell([fnames; varargin{i}']);
elseif iscellstr(varargin{i}) & size(varargin{i},2)==1
fnames=cell([fnames; varargin{i}]);
end
end
endian='b';
nf=length(fnames);
if (strcmp(fnames{nf},'b'))
nf=nf-1;
%fnames{1:(nf-1)}=fnames{1:(nf-1)};
endian='b';
elseif (strcmp(fnames{nf},'l'))
nf=nf-1;
%fnames=fnames{1:(nf-1)};
endian='l';
end
disp(sprintf('%s : using ''%s'' endian type',mfilename,endian))
% expand globs
sacfiles={};k=1;
for i=1:nf
dirlist=dir(fnames{i});
for j=1:length(dirlist)
if ~dirlist(j).isdir
sacfiles{k,1}=dirlist(j).name;
k=k+1;
end
end
end
maxnpts=0;
for i=1:length(sacfiles)
fid=fopen(sacfiles{i},'rb');
if fid==-1
error(sprintf('Could not open SAC file %s',fnames{i}))
end
SACdata(i,1)=readSacHeader(fid,F,K,L);
npts=SACdata(i).trcLen;
if npts>maxnpts
maxnpts=npts;
end
fprintf('Processing file %d: %s\n',i,sacfiles{i});
SeisData(npts,i)=0; % Magnify seis matrix if necessary
SeisData(:,i)=[ readSacData(fid,npts,F+1); zeros(maxnpts-npts,1)]; % Have to pad with zeros if new data have less data points than some previously read file
end
function hdr = readSacHeader(fileId,F,K,L)
% hdr = readSacHeader(FID)
% sacReadAlphaNum reads the SAC-format header fields and returns most of them.
%
% The output variable, 'hdr' is a structure, whose fields are
% the fields as in the SACdata structure generated by SAC's
% matlab command MAT
%
% Created by C. D. Saragiotis, August 5th, 2003, modified by F Tilmann
headerBytes = 632;
chrctr = fread(fileId,headerBytes,'uchar');
chrctr = chrctr(:)';
% Read floats
hdr.times.delta = sacReadFloat(chrctr(1:1+F)); % increment between evenly spaced samples
%hdr.DEPMIN = sacReadFloat(chrctr(5:5+F)); % MINimum value of DEPendent variable
%hdr.DEPMAX = sacReadFloat(chrctr(9:9+F)); % MAXimum value of DEPendent variable
% (not currently used) SCALE = sacReadFloat(chrctr(13:13+F)); % Mult SCALE factor for dependent variable
%hdr.ODELTA = sacReadFloat(chrctr(17:17+F)); % Observd increment if different than DELTA
hdr.times.b = sacReadFloat(chrctr(21:21+F)); % Begining value of the independent variable
hdr.times.e = sacReadFloat(chrctr(25:25+F)); % Ending value of the independent variable
hdr.times.o = sacReadFloat(chrctr(29:29+F)); % event Origin time
hdr.times.a = sacReadFloat(chrctr(33:33+F)); % first Arrival time
hdr.times.t0 = sacReadFloat(chrctr(41:41+F));
hdr.times.t1 = sacReadFloat(chrctr(45:45+F));
hdr.times.t2 = sacReadFloat(chrctr(49:49+F));
hdr.times.t3 = sacReadFloat(chrctr(53:53+F));
hdr.times.t4 = sacReadFloat(chrctr(57:57+F));
hdr.times.t5 = sacReadFloat(chrctr(61:61+F));
hdr.times.t6 = sacReadFloat(chrctr(65:65+F));
hdr.times.t7 = sacReadFloat(chrctr(69:69+F));
hdr.times.t8 = sacReadFloat(chrctr(73:73+F));
hdr.times.t9 = sacReadFloat(chrctr(77:77+F));
hdr.times.f = sacReadFloat(chrctr(81:81+F)); % Fini of event time
hdr.response = sacReadFloat(reshape(chrctr(85:85+10*(F+1)-1),F+1,10)');
hdr.station.stla = sacReadFloat(chrctr(125:125+F)); % STation LAttitude
hdr.station.stlo = sacReadFloat(chrctr(129:129+F)); % STation LOngtitude
hdr.station.stel = sacReadFloat(chrctr(133:133+F)); % STation ELevation
hdr.station.stdp = sacReadFloat(chrctr(137:137+F)); % STation DePth below surface
hdr.event.ecla = sacReadFloat(chrctr(141:141+F)); % EVent LAttitude
hdr.event.evlo = sacReadFloat(chrctr(145:145+F)); % EVent LOngtitude
hdr.event.evel = sacReadFloat(chrctr(149:149+F)); % EVent ELevation
hdr.event.evdp = sacReadFloat(chrctr(153:153+F)); % EVent DePth below surface
hdr.event.mag = sacReadFloat(chrctr(157:157+F)); % EVent DePth below surface
userdata=sacReadFloat(reshape(chrctr(161:161+10*(F+1)-1),F+1,10)');
hdr.evsta.dist = sacReadFloat(chrctr(201:201+F)); % station to event DISTance (km)
hdr.evsta.az = sacReadFloat(chrctr(205:205+F)); % event to station AZimuth (degrees)
hdr.evsta.baz = sacReadFloat(chrctr(209:209+F)); % station to event AZimuth (degrees)
hdr.evsta.gcarc = sacReadFloat(chrctr(213:213+F)); % station to event Great Circle ARC length (degrees)
%hdr.DEPMEN = sacReadFloat(chrctr(225:225+F)); % MEaN value of DEPendent variable
hdr.station.cmpaz = sacReadFloat(chrctr(229:229+F)); % CoMPonent AZimuth (degrees clockwise from north)
hdr.station.cmpinc = sacReadFloat(chrctr(233:233+F)); % CoMPonent INCident angle (degrees from vertical)
hdr.llnl.xminimum = sacReadFloat(chrctr(237:237+L));
hdr.llnl.xmaximum = sacReadFloat(chrctr(241:241+L));
hdr.llnl.yminimum = sacReadFloat(chrctr(245:245+L));
hdr.llnl.ymaximum = sacReadFloat(chrctr(249:249+L));
% Read long integers
hdr.event.nzyear = sacReadLong(chrctr(281:281+L)); % GMT YEAR
hdr.event.nzjday = sacReadLong(chrctr(285:285+L)); % GMT julian DAY
hdr.event.nzhour = sacReadLong(chrctr(289:289+L)); % GMT HOUR
hdr.event.nzmin = sacReadLong(chrctr(293:293+L)); % GMT MINute
hdr.event.nzsec = sacReadLong(chrctr(297:297+L)); % GMT SECond
hdr.event.nzmsec = sacReadLong(chrctr(301:301+L)); % GMT MilliSECond
hdr.llnl.norid = sacReadLong(chrctr(309:309+L));
hdr.llnl.nevid = sacReadLong(chrctr(313:313+L));
hdr.trcLen = sacReadLong(chrctr(317:317+L)); % Number of PoinTS per data component
hdr.llnl.nwfid = sacReadLong(chrctr(325:325+L));
hdr.llnl.nxsize = sacReadLong(chrctr(329:329+L));
hdr.llnl.nysize = sacReadLong(chrctr(333:333+L));
hdr.descrip.iftype = sacReadLong(chrctr(341:341+L)); % File TYPE
hdr.descrip.idep = sacReadLong(chrctr(345:345+L)); % type of DEPendent variable
hdr.descrip.iztype = sacReadLong(chrctr(349:349+L)); % reference time equivalence
hdr.descrip.iinst = sacReadLong(chrctr(357:357+L)); % type of recording INSTrument
% Before there were floats read here?
hdr.descrip.istreg = sacReadLong(chrctr(361:361+F)); % STation geographic REGion
hdr.descrip.ievreg = sacReadLong(chrctr(365:365+F)); % EVent geographic REGion
hdr.descrip.ievtyp = sacReadLong(chrctr(369:369+F)); % EVent geographic REGion
hdr.descrip.iqual = sacReadLong(chrctr(373:373+F)); % QUALity of data
hdr.descrip.isynth = sacReadLong(chrctr(377:377+F)); % SYNTHetic data flag
hdr.event.imagtyp = sacReadLong(chrctr(381:381+F));
hdr.event.imagsrc = sacReadLong(chrctr(385:385+F));
% no logical SAC header variables in matlab SACdata structure!
% previous version set these defaults
% $$$ % SAC defaults
% $$$ hdr.IEVTYPE = 'IUNKN';
% $$$ %IEVTYPE= sacReadFloat(chrctr(369:369+F)); % EVent TYPE
% $$$ hdr.LEVEN = 'TRUE'; % true, if data are EVENly spaced (required)
% $$$ %LEVEN= sacReadFloat(chrctr(421:521+F)); % true, if data are EVENly spaced (required)
% $$$ hdr.LPSPOL = 'FALSE'; % true, if station components have a PoSitive POLarity
% $$$ %LPSPOL= sacReadFloat(chrctr(425:425+F)); % true, if station components have a PoSitive POLarity
% $$$ hdr.LOVROK = 'FALSE'; % true, if it is OK to OVeRwrite this file in disk
% $$$ %LOVROK= sacReadFloat(chrctr(429:429+F)); % true, if it is OK to OVeRwrite this file in disk
% $$$ hdr.LCALDA = 'TRUE'; % true, if DIST, AZ, BAZ and GCARC are to be calculated from station and event coordinates
% $$$ %LCALDA= sacReadFloat(chrctr(433:433+F)); % true, if DIST, AZ, BAZ and GCARC are to be calculated from station and event coordinates
% Read alphanumeric data
hdr.station.kstnm = sacReadAlphaNum(chrctr(441:441+K)); % STation NaMe
hdr.event.kevnm = sacReadAlphaNum(chrctr(449:449+2*(K+1)-1)); % EVent NaMe
%hdr.KHOLE = sacReadAlphaNum(chrctr(465:465+K)); % HOLE identification, if nuclear event
hdr.times.ko = sacReadAlphaNum(chrctr(473:473+K)); % event Origin time identification
hdr.times.ka = sacReadAlphaNum(chrctr(481:481+K)); % first Arrival time identification
hdr.times.kt0 = sacReadAlphaNum(chrctr(489:489+K));
hdr.times.kt1 = sacReadAlphaNum(chrctr(497:497+K));
hdr.times.kt2 = sacReadAlphaNum(chrctr(505:505+K));
hdr.times.kt3 = sacReadAlphaNum(chrctr(513:513+K));
hdr.times.kt4 = sacReadAlphaNum(chrctr(521:521+K));
hdr.times.kt5 = sacReadAlphaNum(chrctr(529:529+K));
hdr.times.kt6 = sacReadAlphaNum(chrctr(537:537+K));
hdr.times.kt7 = sacReadAlphaNum(chrctr(545:545+K));
hdr.times.kt8 = sacReadAlphaNum(chrctr(553:553+K));
hdr.times.kt9 = sacReadAlphaNum(chrctr(561:561+K));
hdr.times.kf = sacReadAlphaNum(chrctr(569:569+K)); % Fini identification
kuser0 = sacReadAlphaNum(chrctr(577:577+K)); % USER-defined variable storage area
kuser1 = sacReadAlphaNum(chrctr(585:585+K)); % USER-defined variable storage area
kuser2 = sacReadAlphaNum(chrctr(593:593+K)); % USER-defined variable storage area
hdr.station.kcmpnm = sacReadAlphaNum(chrctr(601:601+K)); % CoMPonent NaMe
hdr.station.knetwk = sacReadAlphaNum(chrctr(609:609+K)); % name of seismic NETWorK
%hdr.KDATRD = sacReadAlphaNum(chrctr(617:617+K)); % DATa Recording Date onto the computer
%hdr.KINST = sacReadAlphaNum(chrctr(625:625+K)); % generic name of recording INSTrument
usercell=num2cell(userdata);
[usercell{find(userdata==-12345)}]=deal([]);
[hdr.user(1:10).data]=deal(usercell{:});
[hdr.user(1:10).label]=deal(kuser0, kuser1,kuser2,[], [], [], [], [], [], []);
function X = readSacData(fid,N,F)
% function data = readSacData('filename',NPTS,floatByteSize)
chrctr = fread(fid,N*F,'uchar');
x=reshape(chrctr,F,N)';
%x
X = sacReadFloat(x);
function lNumber = sacReadLong(cb)
% reads long integers (4 bytes long)
% cb is the character buffer
global endian
cb = cb(:);
if strcmp(endian,'b')
% BIG ENDIAN
lNumber = (256.^(3:-1:0))*cb;
else
% LITTLE ENDIAN
lNumber = (256.^(0:3))*cb;
end
if lNumber == -12345, lNumber = []; end
function fNumber = sacReadFloat(cb)
% reads floats (4 bytes long)
% cb is the character buffer
global endian
C = size(cb,1);
if strcmp(endian,'b')
% BIG ENDIAN
stringOfBitSequence = [dec2bin(cb(:,1),8) dec2bin(cb(:,2),8) dec2bin(cb(:,3),8) dec2bin(cb(:,4),8)];
else
% LITTLE ENDIAN
stringOfBitSequence = [dec2bin(cb(:,4),8) dec2bin(cb(:,3),8) dec2bin(cb(:,2),8) dec2bin(cb(:,1),8)];
end
bitSequence = stringOfBitSequence=='1';
fSign = -2*bitSequence(:,1)+1;
fExp = bitSequence(:,2:9)*(2.^(7:-1:0)') - 127;
fMantissa = [ones(C,1) bitSequence(:,10:32)]*(2.^(0:-1:-23)');
fNumber = fSign.*fMantissa.*(2.^fExp);
isZeroCheck = sum(bitSequence')'==0;
fNumber = fNumber.*(~isZeroCheck);
if C==1 & fNumber == -12345, fNumber = []; end
function alphaNum = sacReadAlphaNum(cb)
% reads alphanumeric data (8 or 16 bytes long). If it cb is empty, it returns a ' '
% cb is the character buffer
K = max(size(cb));
alphaNumTemp = char(cb);
if K == 8
if alphaNumTemp == '-12345 '
alphaNum = [];
else
alphaNum = alphaNumTemp;
end
else
if K == 16
if alphaNumTemp == '-12345 -12345 ' | alphaNumTemp == '-12345 '
alphaNum = [];
else
alphaNum = alphaNumTemp;
end
end
end
|
github
|
Abakumov/MLIB-master
|
CheckSegyTraceHeader.m
|
.m
|
MLIB-master/OTHER/SegyMAT/CheckSegyTraceHeader.m
| 9,418 |
utf_8
|
8a8ac4e5d40f1e562e9650e81b1308ab
|
% SegyTraceHeader=CheckSegyTraceHeader(SegyTraceHeader);
%
% Checks that all fields of the SegyTraceHeader is set.
% If not, they are initialized.
%
%
% (C) 2004, Thomas Mejer Hansen, [email protected]/[email protected]
%
%
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
%
function SegyTraceHeader=CheckSegyTraceHeader(SegyTraceHeader);
%% SET UP SegyTraceHeader
NA=0;
if ~isfield(SegyTraceHeader,'TraceSequenceLine'), SegyTraceHeader.TraceSequenceLine=NA;end
if ~isfield(SegyTraceHeader,'TraceSequenceFile'), SegyTraceHeader.TraceSequenceFile=NA;end
if ~isfield(SegyTraceHeader,'FieldRecord'), SegyTraceHeader.FieldRecord=NA;end
if ~isfield(SegyTraceHeader,'TraceNumber'), SegyTraceHeader.TraceNumber=NA;end
if ~isfield(SegyTraceHeader,'EnergySourcePoint'), SegyTraceHeader.EnergySourcePoint=NA;end
if ~isfield(SegyTraceHeader,'cdp'), SegyTraceHeader.cdp=NA;end
if ~isfield(SegyTraceHeader,'cdpTrace'), SegyTraceHeader.cdpTrace=NA;end
if ~isfield(SegyTraceHeader,'TraceIdenitifactionCode'), SegyTraceHeader.TraceIdenitifactionCode=NA;end
if ~isfield(SegyTraceHeader,'NSummedTraces'), SegyTraceHeader.NSummedTraces=NA;end
if ~isfield(SegyTraceHeader,'NStackedTraces'), SegyTraceHeader.NStackedTraces=NA;end
if ~isfield(SegyTraceHeader,'DataUse'), SegyTraceHeader.DataUse=NA;end
if ~isfield(SegyTraceHeader,'offset'), SegyTraceHeader.offset=NA;end
if ~isfield(SegyTraceHeader,'ReceiverGroupElevation'), SegyTraceHeader.ReceiverGroupElevation=NA;end
if ~isfield(SegyTraceHeader,'SourceSurfaceElevation'), SegyTraceHeader.SourceSurfaceElevation=NA;end
if ~isfield(SegyTraceHeader,'SourceDepth'), SegyTraceHeader.SourceDepth=NA;end
if ~isfield(SegyTraceHeader,'ReceiverDatumElevation'), SegyTraceHeader.ReceiverDatumElevation=NA;end
if ~isfield(SegyTraceHeader,'SourceDatumElevation'), SegyTraceHeader.SourceDatumElevation=NA;end
if ~isfield(SegyTraceHeader,'SourceWaterDepth'), SegyTraceHeader.SourceWaterDepth=NA;end
if ~isfield(SegyTraceHeader,'GroupWaterDepth'), SegyTraceHeader.GroupWaterDepth=NA;end
if ~isfield(SegyTraceHeader,'ElevationScalar'), SegyTraceHeader.ElevationScalar=NA;end
% Multiply/divide next number for following 4 values
if ~isfield(SegyTraceHeader,'SourceGroupScalar'), SegyTraceHeader.SourceGroupScalar=NA;end
if ~isfield(SegyTraceHeader,'SourceX'), SegyTraceHeader.SourceX=NA;end
if ~isfield(SegyTraceHeader,'SourceY'), SegyTraceHeader.SourceY=NA;end
if ~isfield(SegyTraceHeader,'GroupX'), SegyTraceHeader.GroupX=NA;end
if ~isfield(SegyTraceHeader,'GroupY'), SegyTraceHeader.GroupY=NA;end
if ~isfield(SegyTraceHeader,'CoordinateUnits'), SegyTraceHeader.CoordinateUnits=NA;end
if ~isfield(SegyTraceHeader,'WeatheringVelocity'), SegyTraceHeader.WeatheringVelocity=NA;end
if ~isfield(SegyTraceHeader,'SubWeatheringVelocity'), SegyTraceHeader.SubWeatheringVelocity=NA;end
if ~isfield(SegyTraceHeader,'SourceUpholeTime'), SegyTraceHeader.SourceUpholeTime=NA;end
if ~isfield(SegyTraceHeader,'GroupUpholeTime'), SegyTraceHeader.GroupUpholeTime=NA;end
if ~isfield(SegyTraceHeader,'SourceStaticCorrection'), SegyTraceHeader.SourceStaticCorrection=NA;end
if ~isfield(SegyTraceHeader,'GroupStaticCorrection'), SegyTraceHeader.GroupStaticCorrection=NA;end
if ~isfield(SegyTraceHeader,'TotalStaticApplied'), SegyTraceHeader.TotalStaticApplied=NA;end
if ~isfield(SegyTraceHeader,'LagTimeA'), SegyTraceHeader.LagTimeA=NA;end
if ~isfield(SegyTraceHeader,'LagTimeB'), SegyTraceHeader.LagTimeB=NA;end
if ~isfield(SegyTraceHeader,'DelayRecordingTime'), SegyTraceHeader.DelayRecordingTime=NA;end
if ~isfield(SegyTraceHeader,'MuteTimeStart'), SegyTraceHeader.MuteTimeStart=NA;end
if ~isfield(SegyTraceHeader,'MuteTimeEND'), SegyTraceHeader.MuteTimeEND=NA;end
if ~isfield(SegyTraceHeader,'ns'), SegyTraceHeader.ns=NA;end
if ~isfield(SegyTraceHeader,'dt'), SegyTraceHeader.dt=NA;end
if ~isfield(SegyTraceHeader,'GainType'), SegyTraceHeader.GainType=NA;end
if ~isfield(SegyTraceHeader,'InstrumentGainConstant'), SegyTraceHeader.InstrumentGainConstant=NA;end
if ~isfield(SegyTraceHeader,'InstrumentInitialGain'), SegyTraceHeader.InstrumentInitialGain=NA;end
if ~isfield(SegyTraceHeader,'Correlated'), SegyTraceHeader.Correlated=NA;end
if ~isfield(SegyTraceHeader,'SweepFrequenceStart'), SegyTraceHeader.SweepFrequenceStart=NA;end
if ~isfield(SegyTraceHeader,'SweepFrequenceEnd'), SegyTraceHeader.SweepFrequenceEnd=NA;end
if ~isfield(SegyTraceHeader,'SweepLength'), SegyTraceHeader.SweepLength=NA;end
if ~isfield(SegyTraceHeader,'SweepType'), SegyTraceHeader.SweepType=NA;end
if ~isfield(SegyTraceHeader,'SweepTraceTaperLengthStart'), SegyTraceHeader.SweepTraceTaperLengthStart=NA;end
if ~isfield(SegyTraceHeader,'SweepTraceTaperLengthEnd'), SegyTraceHeader.SweepTraceTaperLengthEnd=NA;end
if ~isfield(SegyTraceHeader,'TaperType'), SegyTraceHeader.TaperType=NA;end
if ~isfield(SegyTraceHeader,'AliasFilterFrequency'), SegyTraceHeader.AliasFilterFrequency=NA;end
if ~isfield(SegyTraceHeader,'AliasFilterSlope'), SegyTraceHeader.AliasFilterSlope=NA;end
if ~isfield(SegyTraceHeader,'NotchFilterFrequency'), SegyTraceHeader.NotchFilterFrequency=NA;end
if ~isfield(SegyTraceHeader,'NotchFilterSlope'), SegyTraceHeader.NotchFilterSlope=NA;end
if ~isfield(SegyTraceHeader,'LowCutFrequency'), SegyTraceHeader.LowCutFrequency=NA;end
if ~isfield(SegyTraceHeader,'HighCutFrequency'), SegyTraceHeader.HighCutFrequency=NA;end
if ~isfield(SegyTraceHeader,'LowCutSlope'), SegyTraceHeader.LowCutSlope=NA;end
if ~isfield(SegyTraceHeader,'HighCutSlope'), SegyTraceHeader.HighCutSlope=NA;end
da=clock;
if ~isfield(SegyTraceHeader,'YearDataRecorded'), SegyTraceHeader.YearDataRecorded=da(1);end
DayOfYear=datenum(0,da(2),da(3)); % 22/7-2002 by Michael Toews ([email protected])
if ~isfield(SegyTraceHeader,'DayOfYear'), SegyTraceHeader.DayOfYear=DayOfYear;end
if ~isfield(SegyTraceHeader,'HourOfDay'), SegyTraceHeader.HourOfDay=da(4);end
if ~isfield(SegyTraceHeader,'MinuteOfHour'), SegyTraceHeader.MinuteOfHour=da(5);end
if ~isfield(SegyTraceHeader,'SecondOfMinute'), SegyTraceHeader.SecondOfMinute=round(da(6));end
if ~isfield(SegyTraceHeader,'TimeBaseCode'), SegyTraceHeader.TimeBaseCode=NA;end
if ~isfield(SegyTraceHeader,'TraceWeightningFactor'), SegyTraceHeader.TraceWeightningFactor=NA;end
if ~isfield(SegyTraceHeader,'GeophoneGroupNumberRoll1'), SegyTraceHeader.GeophoneGroupNumberRoll1=NA;end
if ~isfield(SegyTraceHeader,'GeophoneGroupNumberFirstTraceOrigField'), SegyTraceHeader.GeophoneGroupNumberFirstTraceOrigField=NA;end
if ~isfield(SegyTraceHeader,'GeophoneGroupNumberLastTraceOrigField'), SegyTraceHeader.GeophoneGroupNumberLastTraceOrigField=NA;end
if ~isfield(SegyTraceHeader,'GapSize'), SegyTraceHeader.GapSize=NA;end
if ~isfield(SegyTraceHeader,'OverTravel'), SegyTraceHeader.OverTravel=NA;end
if ~isfield(SegyTraceHeader,'cdpX'), SegyTraceHeader.cdpX=NA;end
if ~isfield(SegyTraceHeader,'cdpY'), SegyTraceHeader.cdpY=NA;end
if ~isfield(SegyTraceHeader,'Inline3D'), SegyTraceHeader.Inline3D=NA;end
if ~isfield(SegyTraceHeader,'Crossline3D'), SegyTraceHeader.Crossline3D=NA;end
if ~isfield(SegyTraceHeader,'ShotPoint'), SegyTraceHeader.ShotPoint=NA;end
if ~isfield(SegyTraceHeader,'ShotPointScalar'), SegyTraceHeader.ShotPointScalar=NA;end
if ~isfield(SegyTraceHeader,'TraceValueMeasurementUnit'), SegyTraceHeader.TraceValueMeasurementUnit=NA;end
if ~isfield(SegyTraceHeader,'TransductionConstantMantissa'), SegyTraceHeader.TransductionConstantMantissa=NA;end
if ~isfield(SegyTraceHeader,'TransductionConstantPower'), SegyTraceHeader.TransductionConstantPower=NA;end
if ~isfield(SegyTraceHeader,'TransductionUnit'), SegyTraceHeader.TransductionUnit=NA;end
if ~isfield(SegyTraceHeader,'TraceIdentifier'), SegyTraceHeader.TraceIdentifier=NA;end
if ~isfield(SegyTraceHeader,'ScalarTraceHeader'), SegyTraceHeader.ScalarTraceHeader=NA;end
if ~isfield(SegyTraceHeader,'SourceType'), SegyTraceHeader.SourceType=NA;end
if ~isfield(SegyTraceHeader,'SourceEnergyDirectionMantissa'), SegyTraceHeader.SourceEnergyDirectionMantissa=NA;end
if ~isfield(SegyTraceHeader,'SourceEnergyDirectionExponent'), SegyTraceHeader.SourceEnergyDirectionExponent=NA;end
if ~isfield(SegyTraceHeader,'SourceMeasurementMantissa'), SegyTraceHeader.SourceMeasurementMantissa=NA;end
if ~isfield(SegyTraceHeader,'SourceMeasurementExponent'), SegyTraceHeader.SourceMeasurementExponent=NA;end
if ~isfield(SegyTraceHeader,'SourceMeasurementUnit'), SegyTraceHeader.SourceMeasurementUnit=NA;end
if ~isfield(SegyTraceHeader,'UnassignedInt1'), SegyTraceHeader.UnassignedInt1=NA;end
if ~isfield(SegyTraceHeader,'UnassignedInt2'), SegyTraceHeader.UnassignedInt2=NA;end
|
github
|
Abakumov/MLIB-master
|
ReadSuFast.m
|
.m
|
MLIB-master/OTHER/SegyMAT/ReadSuFast.m
| 1,615 |
utf_8
|
b0e4202173b5f1f60be77ae2faa9fb1b
|
% ReadSuFast
%
% PURPOSE : reads a SEISMIC section i SU format in big endian format,
% strips the headers and returns the field in the matrix seis.
% If nx==0 and nt<>0, nx will be computed
% If nt==0 and nx<>0, nt will be computed
%
% Call : function seis=ReadSuFast(fileid,nt,nx,'byteorder');
% byteorder : 'l' for little or 'b' for big endian (Default : Native )
%
% BY : TMH 1/8 1997
% Updated by Thomas Mejer Hansen : 22-03-1999
%
function [seis,nt,nx]=ReadSuFast(fileid,nt,nx,byte);
if nargin==4 | nargin==2,
if nargin==2, byte=nt; nt=0; end
if byte=='b'
b_order='ieee-be';
else
b_order='ieee-le';
end
SegymatVerbose(['SU2MAT : Byteorder : ',b_order],2)
else
% USE DEFAULT BYTEORDER
SegymatVerbose(['SU2MAT : Byteorder : DEFAULT'],2)
end
if nargin==1 | nargin==2,
if exist('b_order')==1, fid=fopen(fileid,'r',b_order);
else, fid=fopen(fileid,'r'); end
S0=fread(fid,60,'int16');nt=S0(58);
if nt<0,
% THIS CANNOT BE, MAYBE WRONG BYTE ORDER
SegymatVerbose([mfilename,' : Wrong NT, maybe wrong byte order'])
seis=[];nt=nt;nx=[];
return
end
SegymatVerbose(['nt=',num2str(nt)],2)
nx=0;
fclose(fid);
end
if exist('b_order')==1, fid=fopen(fileid,'r',b_order);
else, fid=fopen(fileid,'r'); end
S=fread(fid,inf,'float');
l=length(S);
if nt==0, nt=l/nx-60; SegymatVerbose(['nt=',num2str(nt)],2);end
if nx==0, nx=l/(nt+60); SegymatVerbose(['nx=',num2str(nx)],2); end,
S=reshape(S,nt+60,nx);
seis=S(61:nt+60,:);
|
github
|
Abakumov/MLIB-master
|
sacpc2mat.m
|
.m
|
MLIB-master/OTHER/SegyMAT/sacpc2mat.m
| 12,238 |
utf_8
|
3de29cc89a474829293e79a5a66c8b4c
|
function [SACdata,SeisData,sacfiles]=sacpc2mat(varargin)
% [SACdata,SeisData,filenames] = SACPCMAT('file1','file2',..., 'filen' )
%
% reads n SAC files file1, file2, filen (SAC files are assumed to have
% PC byte order) and converts them to matlab
% format. The filenames can contain globbing characters (e.g. * and ?).
% These are expanded and all matching files loaded.
%
% SACPCMAT( cellarray ) where cellarray={'file1','file2',...,'filen'}
% is equivalent to the standard form.
%
% SACdata is an n x 1 struct array containing the header variables
% in the same format as is obtained by using MAT function
% of SAC2000.
% SACdata(i).trcLen contains the number of samples.
%
% SeisData is an m x n array (where m=max(npts1, npts2, ...) )
% containing the actual data.
%
% filenames is a n x 1 string cell array with the filenames actually read.
%
% Note that writing
%
% [SACdata,SeisData] = sacsun2mat('file1','file2',..., 'filen' )
%
% is equivalent to the following sequence
%
% sac2000
% READ file1 file2 .. filen
% MAT
%
% (in fact the failure of above sequence to work properly on my
% system motivated this script).
%
%
% SACPC2MAT was written by F Tilmann ([email protected])
% based on sac_sun2pc_mat by C. D. Saragiotis (I copied the
% routines doing the actual work from this code but
% used a different header structure and made the routine
% flexible).
% It was tested on MATLAB5 on a PC but
% should work on newer versions, too.
%
% (C) 2004
%
F = 4-1; % float byte-size minus 1;
K = 8-1; % alphanumeric byte-size minus 1
L = 4-1; % long integer byte-size minus 1;
fnames={};
for i=1:nargin
if ischar(varargin{i})
fnames=cell([fnames; cellstr(varargin{i})]);
elseif iscellstr(varargin{i}) & size(varargin{i},1)==1
fnames=cell([fnames; varargin{i}']);
elseif iscellstr(varargin{i}) & size(varargin{i},2)==1
fnames=cell([fnames; varargin{i}]);
end
end
% expand globs
sacfiles={};k=1;
for i=1:length(fnames)
dirlist=dir(fnames{i});
for j=1:length(dirlist)
if ~dirlist(j).isdir
sacfiles{k,1}=dirlist(j).name;
k=k+1;
end
end
end
maxnpts=0;
for i=1:length(sacfiles)
fid=fopen(sacfiles{i},'rb');
if fid==-1
error(sprintf('Could not open SAC file %s',fnames{i}))
end
SACdata(i,1)=readSacHeader(fid,F,K,L);
npts=SACdata(i).trcLen;
if npts>maxnpts
maxnpts=npts;
end
fprintf('Processing file %d: %s\n',i,sacfiles{i});
SeisData(npts,i)=0; % Magnify seis matrix if necessary
SeisData(:,i)=[ readSacData(fid,npts,F+1); zeros(maxnpts-npts,1)]; % Have to pad with zeros if new data have less data points than some previously read file
end
function hdr = readSacHeader(fileId,F,K,L)
% hdr = readSacHeader(FID)
% sacReadAlphaNum reads the SAC-format header fields and returns most of them.
%
% The output variable, 'hdr' is a structure, whose fields are
% the fields as in the SACdata structure generated by SAC's
% matlab command MAT
%
% Created by C. D. Saragiotis, August 5th, 2003, modified by F Tilmann
headerBytes = 632;
chrctr = fread(fileId,headerBytes,'uchar');
chrctr = chrctr(:)';
% Read floats
hdr.times.delta = sacReadFloat(chrctr(1:1+F)); % increment between evenly spaced samples
%hdr.DEPMIN = sacReadFloat(chrctr(5:5+F)); % MINimum value of DEPendent variable
%hdr.DEPMAX = sacReadFloat(chrctr(9:9+F)); % MAXimum value of DEPendent variable
% (not currently used) SCALE = sacReadFloat(chrctr(13:13+F)); % Mult SCALE factor for dependent variable
%hdr.ODELTA = sacReadFloat(chrctr(17:17+F)); % Observd increment if different than DELTA
hdr.times.b = sacReadFloat(chrctr(21:21+F)); % Begining value of the independent variable
hdr.times.e = sacReadFloat(chrctr(25:25+F)); % Ending value of the independent variable
hdr.times.o = sacReadFloat(chrctr(29:29+F)); % event Origin time
hdr.times.a = sacReadFloat(chrctr(33:33+F)); % first Arrival time
hdr.times.t0 = sacReadFloat(chrctr(41:41+F));
hdr.times.t1 = sacReadFloat(chrctr(45:45+F));
hdr.times.t2 = sacReadFloat(chrctr(49:49+F));
hdr.times.t3 = sacReadFloat(chrctr(53:53+F));
hdr.times.t4 = sacReadFloat(chrctr(57:57+F));
hdr.times.t5 = sacReadFloat(chrctr(61:61+F));
hdr.times.t6 = sacReadFloat(chrctr(65:65+F));
hdr.times.t7 = sacReadFloat(chrctr(69:69+F));
hdr.times.t8 = sacReadFloat(chrctr(73:73+F));
hdr.times.t9 = sacReadFloat(chrctr(77:77+F));
hdr.times.f = sacReadFloat(chrctr(81:81+F)); % Fini of event time
hdr.response = sacReadFloat(reshape(chrctr(85:85+10*(F+1)-1),F+1,10)');
hdr.station.stla = sacReadFloat(chrctr(125:125+F)); % STation LAttitude
hdr.station.stlo = sacReadFloat(chrctr(129:129+F)); % STation LOngtitude
hdr.station.stel = sacReadFloat(chrctr(133:133+F)); % STation ELevation
hdr.station.stdp = sacReadFloat(chrctr(137:137+F)); % STation DePth below surface
hdr.event.ecla = sacReadFloat(chrctr(141:141+F)); % EVent LAttitude
hdr.event.evlo = sacReadFloat(chrctr(145:145+F)); % EVent LOngtitude
hdr.event.evel = sacReadFloat(chrctr(149:149+F)); % EVent ELevation
hdr.event.evdp = sacReadFloat(chrctr(153:153+F)); % EVent DePth below surface
hdr.event.mag = sacReadFloat(chrctr(157:157+F)); % EVent DePth below surface
userdata=sacReadFloat(reshape(chrctr(161:161+10*(F+1)-1),F+1,10)');
hdr.evsta.dist = sacReadFloat(chrctr(201:201+F)); % station to event DISTance (km)
hdr.evsta.az = sacReadFloat(chrctr(205:205+F)); % event to station AZimuth (degrees)
hdr.evsta.baz = sacReadFloat(chrctr(209:209+F)); % station to event AZimuth (degrees)
hdr.evsta.gcarc = sacReadFloat(chrctr(213:213+F)); % station to event Great Circle ARC length (degrees)
%hdr.DEPMEN = sacReadFloat(chrctr(225:225+F)); % MEaN value of DEPendent variable
hdr.station.cmpaz = sacReadFloat(chrctr(229:229+F)); % CoMPonent AZimuth (degrees clockwise from north)
hdr.station.cmpinc = sacReadFloat(chrctr(233:233+F)); % CoMPonent INCident angle (degrees from vertical)
hdr.llnl.xminimum = sacReadFloat(chrctr(237:237+L));
hdr.llnl.xmaximum = sacReadFloat(chrctr(241:241+L));
hdr.llnl.yminimum = sacReadFloat(chrctr(245:245+L));
hdr.llnl.ymaximum = sacReadFloat(chrctr(249:249+L));
% Read long integers
hdr.event.nzyear = sacReadLong(chrctr(281:281+L)); % GMT YEAR
hdr.event.nzjday = sacReadLong(chrctr(285:285+L)); % GMT julian DAY
hdr.event.nzhour = sacReadLong(chrctr(289:289+L)); % GMT HOUR
hdr.event.nzmin = sacReadLong(chrctr(293:293+L)); % GMT MINute
hdr.event.nzsec = sacReadLong(chrctr(297:297+L)); % GMT SECond
hdr.event.nzmsec = sacReadLong(chrctr(301:301+L)); % GMT MilliSECond
hdr.llnl.norid = sacReadLong(chrctr(309:309+L));
hdr.llnl.nevid = sacReadLong(chrctr(313:313+L));
hdr.trcLen = sacReadLong(chrctr(317:317+L)); % Number of PoinTS per data component
hdr.llnl.nwfid = sacReadLong(chrctr(325:325+L));
hdr.llnl.nxsize = sacReadLong(chrctr(329:329+L));
hdr.llnl.nysize = sacReadLong(chrctr(333:333+L));
hdr.descrip.iftype = sacReadLong(chrctr(341:341+L)); % File TYPE
hdr.descrip.idep = sacReadLong(chrctr(345:345+L)); % type of DEPendent variable
hdr.descrip.iztype = sacReadLong(chrctr(349:349+L)); % reference time equivalence
hdr.descrip.iinst = sacReadLong(chrctr(357:357+L)); % type of recording INSTrument
% Before there were floats read here?
hdr.descrip.istreg = sacReadLong(chrctr(361:361+F)); % STation geographic REGion
hdr.descrip.ievreg = sacReadLong(chrctr(365:365+F)); % EVent geographic REGion
hdr.descrip.ievtyp = sacReadLong(chrctr(369:369+F)); % EVent geographic REGion
hdr.descrip.iqual = sacReadLong(chrctr(373:373+F)); % QUALity of data
hdr.descrip.isynth = sacReadLong(chrctr(377:377+F)); % SYNTHetic data flag
hdr.event.imagtyp = sacReadLong(chrctr(381:381+F));
hdr.event.imagsrc = sacReadLong(chrctr(385:385+F));
% no logical SAC header variables in matlab SACdata structure!
% previous version set these defaults
% $$$ % SAC defaults
% $$$ hdr.IEVTYPE = 'IUNKN';
% $$$ %IEVTYPE= sacReadFloat(chrctr(369:369+F)); % EVent TYPE
% $$$ hdr.LEVEN = 'TRUE'; % true, if data are EVENly spaced (required)
% $$$ %LEVEN= sacReadFloat(chrctr(421:521+F)); % true, if data are EVENly spaced (required)
% $$$ hdr.LPSPOL = 'FALSE'; % true, if station components have a PoSitive POLarity
% $$$ %LPSPOL= sacReadFloat(chrctr(425:425+F)); % true, if station components have a PoSitive POLarity
% $$$ hdr.LOVROK = 'FALSE'; % true, if it is OK to OVeRwrite this file in disk
% $$$ %LOVROK= sacReadFloat(chrctr(429:429+F)); % true, if it is OK to OVeRwrite this file in disk
% $$$ hdr.LCALDA = 'TRUE'; % true, if DIST, AZ, BAZ and GCARC are to be calculated from station and event coordinates
% $$$ %LCALDA= sacReadFloat(chrctr(433:433+F)); % true, if DIST, AZ, BAZ and GCARC are to be calculated from station and event coordinates
% Read alphanumeric data
hdr.station.kstnm = sacReadAlphaNum(chrctr(441:441+K)); % STation NaMe
hdr.event.kevnm = sacReadAlphaNum(chrctr(449:449+2*(K+1)-1)); % EVent NaMe
%hdr.KHOLE = sacReadAlphaNum(chrctr(465:465+K)); % HOLE identification, if nuclear event
hdr.times.ko = sacReadAlphaNum(chrctr(473:473+K)); % event Origin time identification
hdr.times.ka = sacReadAlphaNum(chrctr(481:481+K)); % first Arrival time identification
hdr.times.kt0 = sacReadAlphaNum(chrctr(489:489+K));
hdr.times.kt1 = sacReadAlphaNum(chrctr(497:497+K));
hdr.times.kt2 = sacReadAlphaNum(chrctr(505:505+K));
hdr.times.kt3 = sacReadAlphaNum(chrctr(513:513+K));
hdr.times.kt4 = sacReadAlphaNum(chrctr(521:521+K));
hdr.times.kt5 = sacReadAlphaNum(chrctr(529:529+K));
hdr.times.kt6 = sacReadAlphaNum(chrctr(537:537+K));
hdr.times.kt7 = sacReadAlphaNum(chrctr(545:545+K));
hdr.times.kt8 = sacReadAlphaNum(chrctr(553:553+K));
hdr.times.kt9 = sacReadAlphaNum(chrctr(561:561+K));
hdr.times.kf = sacReadAlphaNum(chrctr(569:569+K)); % Fini identification
kuser0 = sacReadAlphaNum(chrctr(577:577+K)); % USER-defined variable storage area
kuser1 = sacReadAlphaNum(chrctr(585:585+K)); % USER-defined variable storage area
kuser2 = sacReadAlphaNum(chrctr(593:593+K)); % USER-defined variable storage area
hdr.station.kcmpnm = sacReadAlphaNum(chrctr(601:601+K)); % CoMPonent NaMe
hdr.station.knetwk = sacReadAlphaNum(chrctr(609:609+K)); % name of seismic NETWorK
%hdr.KDATRD = sacReadAlphaNum(chrctr(617:617+K)); % DATa Recording Date onto the computer
%hdr.KINST = sacReadAlphaNum(chrctr(625:625+K)); % generic name of recording INSTrument
usercell=num2cell(userdata);
[usercell{find(userdata==-12345)}]=deal([]);
[hdr.user(1:10).data]=deal(usercell{:});
[hdr.user(1:10).label]=deal(kuser0, kuser1,kuser2,[], [], [], [], [], [], []);
function X = readSacData(fid,N,F)
% function data = readSacData('filename',NPTS,floatByteSize)
chrctr = fread(fid,N*F,'uchar');
x=reshape(chrctr,F,N)';
%x
X = sacReadFloat(x);
function lNumber = sacReadLong(cb)
% reads long integers (4 bytes long)
% cb is the character buffer
cb = cb(:);
% SUN sac format use: lNumber = (256.^(3:-1:0))*cb;
lNumber = (256.^(0:3))*cb; % changed line
if lNumber == -12345, lNumber = []; end
function fNumber = sacReadFloat(cb)
% reads floats (4 bytes long)
% cb is the character buffer
C = size(cb,1);
% SUN sac format use: stringOfBitSequence = [dec2bin(cb(:,1),8) dec2bin(cb(:,2),8) dec2bin(cb(:,3),8) dec2bin(cb(:,4),8)];
stringOfBitSequence = [dec2bin(cb(:,4),8) dec2bin(cb(:,3),8) ...
dec2bin(cb(:,2),8) dec2bin(cb(:,1),8)]; %changed line
bitSequence = stringOfBitSequence=='1';
fSign = -2*bitSequence(:,1)+1;
fExp = bitSequence(:,2:9)*(2.^(7:-1:0)') - 127;
fMantissa = [ones(C,1) bitSequence(:,10:32)]*(2.^(0:-1:-23)');
fNumber = fSign.*fMantissa.*(2.^fExp);
isZeroCheck = sum(bitSequence')'==0;
fNumber = fNumber.*(~isZeroCheck);
if C==1 & fNumber == -12345, fNumber = []; end
function alphaNum = sacReadAlphaNum(cb)
% reads alphanumeric data (8 or 16 bytes long). If it cb is empty, it returns a ' '
% cb is the character buffer
K = max(size(cb));
alphaNumTemp = char(cb);
if K == 8
if alphaNumTemp == '-12345 '
alphaNum = [];
else
alphaNum = alphaNumTemp;
end
else
if K == 16
if alphaNumTemp == '-12345 -12345 ' | alphaNumTemp == '-12345 '
alphaNum = [];
else
alphaNum = alphaNumTemp;
end
end
end
|
github
|
Abakumov/MLIB-master
|
GetSegyTraceData.m
|
.m
|
MLIB-master/OTHER/SegyMAT/GetSegyTraceData.m
| 2,761 |
utf_8
|
4782c349465a99ec22ceefb699a275a2
|
% GetSegyTraceData : Get Segy trace data if filehandle
%
% Call :
%
% tracedata=GetSegyTraceData(segyid,ns,SegyHeader,SkipData
%
%
% (C) 2001-2004 Thomas Mejer Hansen, [email protected]/[email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
%
function tracedata=GetSegyTraceData(segyid,ns,SegyHeader,SkipData)
%
% Get Segy Trace Data.
%
%
SkipData=[];
if nargin==0,
SegymatVerbose(exist('segyid'))
SegymatVerbose([mfilename,' : SEGYID not specified - exiting'])
tracedata=[];
return
end
if nargin==1
SegymatVerbose([mfilename,' : NS not specified - exiting'])
tracedata=[];
return
end
if nargin==2
SegyHeader.DataFormat='float32';
SegyHeader.BytesPerSample=32;
SegyHeader.DataSampleFormat=5; % IEEE
SegymatVerbose(['Dataformat not specified - dataformat->',SegyHeader.DataFormat])
end;
if isempty(SkipData)==1, SkipData=0; end
Revision=SegyHeader.SegyFormatRevisionNumber;
if Revision>0, Revision=1; end
Format=SegyHeader.Rev(Revision+1).DataSampleFormat(SegyHeader.DataSampleFormat).format;
BPS=SegyHeader.Rev(Revision+1).DataSampleFormat(SegyHeader.DataSampleFormat).bps;
if (SkipData==1)
SkipBytes=ns*BPS/8;
fseek(segyid,SkipBytes,'cof');
tracedata=[];
else
% SegymatVerbose([mfilename,' : ',Format,'. ns=',num2str(ns)])
try
tracedata=fread(segyid,ns,Format);
catch
SegymatVerbose([mfilename,' : Error using fread - Possibly ''ns'' is negative -' ...
' check byteorder-'])
tracedata=[];
end
if (strcmp(Format,'uint32')==1), % IBM FLOATING POINT
% CONVERT FROM FLOATING POINT
verbose=1;
if verbose>1, SegymatVerbose([mfilename,'Converting from IBM, DataFormat :',SegyHeader.DataFormat]); end
try
tracedata=ibm2num(uint32(tracedata));
catch
% SegymatVerbose([mfilename,' : SOMETHING BAD HAPPENED WHEN CONVERTING FROM IBM FLOATS TO IEEE. ARE YOU SURE DATA ARE IBM FLOAT FORMATTED ?' ])
% tracedata=0.*tracedata;
% return
end
end;
end
|
github
|
Abakumov/MLIB-master
|
sacsun2mat.m
|
.m
|
MLIB-master/OTHER/SegyMAT/sacsun2mat.m
| 12,020 |
utf_8
|
cc2301b099208443313a2f9b49135cab
|
function [SACdata,SeisData,sacfiles]=sacsun2mat(varargin)
% [SACdata,SeisData,filenames] = SACSUN2MAT('file1','file2',..., 'filen' )
%
% reads n SAC files file1, file2, filen (SAC files are assumed to have
% SUN byte order) and converts them to matlab
% format. The filenames can contain globbing characters (e.g. * and ?).
% These are expanded and all matching files loaded.
%
% SACSUN2MAT( cellarray ) where cellarray={'file1','file2',...,'filen'}
% is equivalent to the standard form.
%
% SACdata is an n x 1 struct array containing the header variables
% in the same format as is obtained by using MAT function
% of SAC2000.
% SACdata(i).trcLen contains the number of samples.
%
% SeisData is an m x n array (where m=max(npts1, npts2, ...) )
% containing the actual data.
%
% filenames is a n x 1 string cell array with the filenames actually read.
%
% Note that writing
%
% [SACdata,SeisData] = sacsun2mat('file1','file2',..., 'filen' )
%
% is equivalent to the following sequence
%
% sac2000
% READ file1 file2 .. filen
% MAT
%
% (in fact the failure of above sequence to work properly on my
% system motivated this script).
%
%
% SACSUN2MAT was written by F Tilmann ([email protected])
% based on sac_sun2pc_mat by C. D. Saragiotis (I copied the
% routines doing the actual work from this code but
% used a different header structure and made the routine
% flexible).
% It was tested on MATLAB5 on a PC but
% should work on newer versions, too.
%
% (C) 2004
%
F = 4-1; % float byte-size minus 1;
K = 8-1; % alphanumeric byte-size minus 1
L = 4-1; % long integer byte-size minus 1;
fnames={};
for i=1:nargin
if ischar(varargin{i})
fnames=cell([fnames; cellstr(varargin{i})]);
elseif iscellstr(varargin{i}) & size(varargin{i},1)==1
fnames=cell([fnames; varargin{i}']);
elseif iscellstr(varargin{i}) & size(varargin{i},2)==1
fnames=cell([fnames; varargin{i}]);
end
end
% expand globs
sacfiles={};k=1;
for i=1:length(fnames)
dirlist=dir(fnames{i});
for j=1:length(dirlist)
if ~dirlist(j).isdir
sacfiles{k,1}=dirlist(j).name;
k=k+1;
end
end
end
maxnpts=0;
for i=1:length(sacfiles)
fid=fopen(sacfiles{i},'rb');
if fid==-1
error(sprintf('Could not open SAC file %s',fnames{i}))
end
SACdata(i,1)=readSacHeader(fid,F,K,L);
npts=SACdata(i).trcLen;
if npts>maxnpts
maxnpts=npts;
end
fprintf('Processing file %d: %s\n',i,sacfiles{i});
SeisData(npts,i)=0; % Magnify seis matrix if necessary
SeisData(:,i)=[ readSacData(fid,npts,F+1); zeros(maxnpts-npts,1)]; % Have to pad with zeros if new data have less data points than some previously read file
end
function hdr = readSacHeader(fileId,F,K,L)
% hdr = readSacHeader(FID)
% sacReadAlphaNum reads the SAC-format header fields and returns most of them.
%
% The output variable, 'hdr' is a structure, whose fields are
% the fields as in the SACdata structure generated by SAC's
% matlab command MAT
%
% Created by C. D. Saragiotis, August 5th, 2003, modified by F Tilmann
headerBytes = 632;
chrctr = fread(fileId,headerBytes,'uchar');
chrctr = chrctr(:)';
% Read floats
hdr.times.delta = sacReadFloat(chrctr(1:1+F)); % increment between evenly spaced samples
%hdr.DEPMIN = sacReadFloat(chrctr(5:5+F)); % MINimum value of DEPendent variable
%hdr.DEPMAX = sacReadFloat(chrctr(9:9+F)); % MAXimum value of DEPendent variable
% (not currently used) SCALE = sacReadFloat(chrctr(13:13+F)); % Mult SCALE factor for dependent variable
%hdr.ODELTA = sacReadFloat(chrctr(17:17+F)); % Observd increment if different than DELTA
hdr.times.b = sacReadFloat(chrctr(21:21+F)); % Begining value of the independent variable
hdr.times.e = sacReadFloat(chrctr(25:25+F)); % Ending value of the independent variable
hdr.times.o = sacReadFloat(chrctr(29:29+F)); % event Origin time
hdr.times.a = sacReadFloat(chrctr(33:33+F)); % first Arrival time
hdr.times.t0 = sacReadFloat(chrctr(41:41+F));
hdr.times.t1 = sacReadFloat(chrctr(45:45+F));
hdr.times.t2 = sacReadFloat(chrctr(49:49+F));
hdr.times.t3 = sacReadFloat(chrctr(53:53+F));
hdr.times.t4 = sacReadFloat(chrctr(57:57+F));
hdr.times.t5 = sacReadFloat(chrctr(61:61+F));
hdr.times.t6 = sacReadFloat(chrctr(65:65+F));
hdr.times.t7 = sacReadFloat(chrctr(69:69+F));
hdr.times.t8 = sacReadFloat(chrctr(73:73+F));
hdr.times.t9 = sacReadFloat(chrctr(77:77+F));
hdr.times.f = sacReadFloat(chrctr(81:81+F)); % Fini of event time
hdr.response = sacReadFloat(reshape(chrctr(85:85+10*(F+1)-1),F+1,10)');
hdr.station.stla = sacReadFloat(chrctr(125:125+F)); % STation LAttitude
hdr.station.stlo = sacReadFloat(chrctr(129:129+F)); % STation LOngtitude
hdr.station.stel = sacReadFloat(chrctr(133:133+F)); % STation ELevation
hdr.station.stdp = sacReadFloat(chrctr(137:137+F)); % STation DePth below surface
hdr.event.ecla = sacReadFloat(chrctr(141:141+F)); % EVent LAttitude
hdr.event.evlo = sacReadFloat(chrctr(145:145+F)); % EVent LOngtitude
hdr.event.evel = sacReadFloat(chrctr(149:149+F)); % EVent ELevation
hdr.event.evdp = sacReadFloat(chrctr(153:153+F)); % EVent DePth below surface
hdr.event.mag = sacReadFloat(chrctr(157:157+F)); % EVent DePth below surface
userdata=sacReadFloat(reshape(chrctr(161:161+10*(F+1)-1),F+1,10)');
hdr.evsta.dist = sacReadFloat(chrctr(201:201+F)); % station to event DISTance (km)
hdr.evsta.az = sacReadFloat(chrctr(205:205+F)); % event to station AZimuth (degrees)
hdr.evsta.baz = sacReadFloat(chrctr(209:209+F)); % station to event AZimuth (degrees)
hdr.evsta.gcarc = sacReadFloat(chrctr(213:213+F)); % station to event Great Circle ARC length (degrees)
%hdr.DEPMEN = sacReadFloat(chrctr(225:225+F)); % MEaN value of DEPendent variable
hdr.station.cmpaz = sacReadFloat(chrctr(229:229+F)); % CoMPonent AZimuth (degrees clockwise from north)
hdr.station.cmpinc = sacReadFloat(chrctr(233:233+F)); % CoMPonent INCident angle (degrees from vertical)
hdr.llnl.xminimum = sacReadFloat(chrctr(237:237+L));
hdr.llnl.xmaximum = sacReadFloat(chrctr(241:241+L));
hdr.llnl.yminimum = sacReadFloat(chrctr(245:245+L));
hdr.llnl.ymaximum = sacReadFloat(chrctr(249:249+L));
% Read long integers
hdr.event.nzyear = sacReadLong(chrctr(281:281+L)); % GMT YEAR
hdr.event.nzjday = sacReadLong(chrctr(285:285+L)); % GMT julian DAY
hdr.event.nzhour = sacReadLong(chrctr(289:289+L)); % GMT HOUR
hdr.event.nzmin = sacReadLong(chrctr(293:293+L)); % GMT MINute
hdr.event.nzsec = sacReadLong(chrctr(297:297+L)); % GMT SECond
hdr.event.nzmsec = sacReadLong(chrctr(301:301+L)); % GMT MilliSECond
hdr.llnl.norid = sacReadLong(chrctr(309:309+L));
hdr.llnl.nevid = sacReadLong(chrctr(313:313+L));
hdr.trcLen = sacReadLong(chrctr(317:317+L)); % Number of PoinTS per data component
hdr.llnl.nwfid = sacReadLong(chrctr(325:325+L));
hdr.llnl.nxsize = sacReadLong(chrctr(329:329+L));
hdr.llnl.nysize = sacReadLong(chrctr(333:333+L));
hdr.descrip.iftype = sacReadLong(chrctr(341:341+L)); % File TYPE
hdr.descrip.idep = sacReadLong(chrctr(345:345+L)); % type of DEPendent variable
hdr.descrip.iztype = sacReadLong(chrctr(349:349+L)); % reference time equivalence
hdr.descrip.iinst = sacReadLong(chrctr(357:357+L)); % type of recording INSTrument
% Before there were floats read here?
hdr.descrip.istreg = sacReadLong(chrctr(361:361+F)); % STation geographic REGion
hdr.descrip.ievreg = sacReadLong(chrctr(365:365+F)); % EVent geographic REGion
hdr.descrip.ievtyp = sacReadLong(chrctr(369:369+F)); % EVent geographic REGion
hdr.descrip.iqual = sacReadLong(chrctr(373:373+F)); % QUALity of data
hdr.descrip.isynth = sacReadLong(chrctr(377:377+F)); % SYNTHetic data flag
hdr.event.imagtyp = sacReadLong(chrctr(381:381+F));
hdr.event.imagsrc = sacReadLong(chrctr(385:385+F));
% no logical SAC header variables in matlab SACdata structure!
% previous version set these defaults
% $$$ % SAC defaults
% $$$ hdr.IEVTYPE = 'IUNKN';
% $$$ %IEVTYPE= sacReadFloat(chrctr(369:369+F)); % EVent TYPE
% $$$ hdr.LEVEN = 'TRUE'; % true, if data are EVENly spaced (required)
% $$$ %LEVEN= sacReadFloat(chrctr(421:521+F)); % true, if data are EVENly spaced (required)
% $$$ hdr.LPSPOL = 'FALSE'; % true, if station components have a PoSitive POLarity
% $$$ %LPSPOL= sacReadFloat(chrctr(425:425+F)); % true, if station components have a PoSitive POLarity
% $$$ hdr.LOVROK = 'FALSE'; % true, if it is OK to OVeRwrite this file in disk
% $$$ %LOVROK= sacReadFloat(chrctr(429:429+F)); % true, if it is OK to OVeRwrite this file in disk
% $$$ hdr.LCALDA = 'TRUE'; % true, if DIST, AZ, BAZ and GCARC are to be calculated from station and event coordinates
% $$$ %LCALDA= sacReadFloat(chrctr(433:433+F)); % true, if DIST, AZ, BAZ and GCARC are to be calculated from station and event coordinates
% Read alphanumeric data
hdr.station.kstnm = sacReadAlphaNum(chrctr(441:441+K)); % STation NaMe
hdr.event.kevnm = sacReadAlphaNum(chrctr(449:449+2*(K+1)-1)); % EVent NaMe
%hdr.KHOLE = sacReadAlphaNum(chrctr(465:465+K)); % HOLE identification, if nuclear event
hdr.times.ko = sacReadAlphaNum(chrctr(473:473+K)); % event Origin time identification
hdr.times.ka = sacReadAlphaNum(chrctr(481:481+K)); % first Arrival time identification
hdr.times.kt0 = sacReadAlphaNum(chrctr(489:489+K));
hdr.times.kt1 = sacReadAlphaNum(chrctr(497:497+K));
hdr.times.kt2 = sacReadAlphaNum(chrctr(505:505+K));
hdr.times.kt3 = sacReadAlphaNum(chrctr(513:513+K));
hdr.times.kt4 = sacReadAlphaNum(chrctr(521:521+K));
hdr.times.kt5 = sacReadAlphaNum(chrctr(529:529+K));
hdr.times.kt6 = sacReadAlphaNum(chrctr(537:537+K));
hdr.times.kt7 = sacReadAlphaNum(chrctr(545:545+K));
hdr.times.kt8 = sacReadAlphaNum(chrctr(553:553+K));
hdr.times.kt9 = sacReadAlphaNum(chrctr(561:561+K));
hdr.times.kf = sacReadAlphaNum(chrctr(569:569+K)); % Fini identification
kuser0 = sacReadAlphaNum(chrctr(577:577+K)); % USER-defined variable storage area
kuser1 = sacReadAlphaNum(chrctr(585:585+K)); % USER-defined variable storage area
kuser2 = sacReadAlphaNum(chrctr(593:593+K)); % USER-defined variable storage area
hdr.station.kcmpnm = sacReadAlphaNum(chrctr(601:601+K)); % CoMPonent NaMe
hdr.station.knetwk = sacReadAlphaNum(chrctr(609:609+K)); % name of seismic NETWorK
%hdr.KDATRD = sacReadAlphaNum(chrctr(617:617+K)); % DATa Recording Date onto the computer
%hdr.KINST = sacReadAlphaNum(chrctr(625:625+K)); % generic name of recording INSTrument
usercell=num2cell(userdata);
[usercell{find(userdata==-12345)}]=deal([]);
[hdr.user(1:10).data]=deal(usercell{:});
[hdr.user(1:10).label]=deal(kuser0, kuser1,kuser2,[], [], [], [], [], [], []);
function X = readSacData(fid,N,F)
% function data = readSacData('filename',NPTS,floatByteSize)
chrctr = fread(fid,N*F,'uchar');
x=reshape(chrctr,F,N)';
%x
X = sacReadFloat(x);
function lNumber = sacReadLong(cb)
% reads long integers (4 bytes long)
% cb is the character buffer
cb = cb(:);
lNumber = (256.^(3:-1:0))*cb;
if lNumber == -12345, lNumber = []; end
function fNumber = sacReadFloat(cb)
% reads floats (4 bytes long)
% cb is the character buffer
C = size(cb,1);
stringOfBitSequence = [dec2bin(cb(:,1),8) dec2bin(cb(:,2),8) dec2bin(cb(:,3),8) dec2bin(cb(:,4),8)];
bitSequence = stringOfBitSequence=='1';
fSign = -2*bitSequence(:,1)+1;
fExp = bitSequence(:,2:9)*(2.^(7:-1:0)') - 127;
fMantissa = [ones(C,1) bitSequence(:,10:32)]*(2.^(0:-1:-23)');
fNumber = fSign.*fMantissa.*(2.^fExp);
isZeroCheck = sum(bitSequence')'==0;
fNumber = fNumber.*(~isZeroCheck);
if C==1 & fNumber == -12345, fNumber = []; end
function alphaNum = sacReadAlphaNum(cb)
% reads alphanumeric data (8 or 16 bytes long). If it cb is empty, it returns a ' '
% cb is the character buffer
K = max(size(cb));
alphaNumTemp = char(cb);
if K == 8
if alphaNumTemp == '-12345 '
alphaNum = [];
else
alphaNum = alphaNumTemp;
end
else
if K == 16
if alphaNumTemp == '-12345 -12345 ' | alphaNumTemp == '-12345 '
alphaNum = [];
else
alphaNum = alphaNumTemp;
end
end
end
|
github
|
Abakumov/MLIB-master
|
ReadSegyFast.m
|
.m
|
MLIB-master/OTHER/SegyMAT/ReadSegyFast.m
| 7,428 |
utf_8
|
2cb9531a3c43ef0198323dcfb2203951
|
% ReadSegyFast : Reads a SEG Y rev 1 formatted file, without header values (faster than ReadSegy)
%
% Call :
% [Data]=ReadSegyFast(filename);
% and equivalent to :
% [Data]=ReadSegy(filename);
%
%
% Read only the data of a SegFile - NOT Their headers.
% Much faster than ReadSegy
%
% 'minmax', 'skip'
%
% Implemented using the syntax of the SEG-Y revised format :
% SEGY-Y rev 0, SEG-Y rev 1 as described in
% http://seg.org/publications/tech-stand/
%
% Extended Textual Header is not yet tested
% If you would like it implemented, please send me an SEGY file with
% that sort of information, as well as a description of the segy file
%
%
% (C) 2001, Thomas Mejer Hansen, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
%
%
%
%
function [Data]=ReadSegyFast(filename,varargin);
mfilename='ReadSegyFast';
if nargin==0,
SegymatVerbose([mfilename,' : ', filename,' does not exist !'])
Data=[];SegyTraceHeaders=[];SegyHeader=[];HeaderInfo=[];
return
end
% Initialize varargin values
dsf=[];
revision=[];
endian_tight=[];
tmin=[];tmax=[];
headermin=[];headermax=[];header=[];
jump=[];
SegyHeader=[];
segyid = fopen(filename,'r','b'); % ALL DISK FILES ARE IN BIG
% ENDIAN FORMAT, ACCORDING TO SEG
% Y rev 1
fseek(segyid,0,'eof');
BytesInFile = ftell(segyid);
fseek(segyid,0,'bof');
ninput=nargin;
% NEXT TWO LINES TO ENUSRE THAT VARARGIN CAN BE PASSED TO FUNCTION
if ninput==2
% CALL USING VARARGIN
ninput=1+length(varargin{1});
varargin=varargin{1};
else
% DIRECT CALL
ninput=length(varargin);
end
% TRANSFORM VARARGING INTO PARAMETERS
cargin=1;
while (cargin<ninput)
if strcmp(varargin{cargin},'jump')
cargin=cargin+1;
eval(['jump=',num2str(varargin{cargin}),';']);
SegymatVerbose(['JUMP : Read only every ',num2str(jump),'th trace'])
end
if strcmp(varargin{cargin},'minmax')
cargin=cargin+1;
eval(['header=''',varargin{cargin},''';']);
cargin=cargin+1;
eval(['headermin=',num2str(varargin{cargin}),';']);
cargin=cargin+1;
eval(['headermax=',num2str(varargin{cargin}),';']);
SegymatVerbose(['MIN MAX : Using header ',header,' from ',num2str(headermin),' to ',num2str(headermax)])
end
if strcmp(varargin{cargin},'trange')
cargin=cargin+1;
eval(['tmin=',num2str(varargin{cargin}),';']);
cargin=cargin+1;
eval(['tmax=',num2str(varargin{cargin}),';']);
SegymatVerbose(['TRANGE : tmin=',num2str(tmin),' tmax=',num2str(tmax)])
end
if strcmp(varargin{cargin},'revision')
cargin=cargin+1;
eval(['revision=',num2str(varargin{cargin}),';']);
SegymatVerbose(['USING REVISION : rev=',num2str(revision)])
end
if strcmp(varargin{cargin},'dsf')
cargin=cargin+1;
eval(['dsf=',num2str(varargin{cargin}),';']);
SegymatVerbose(['USING Data Sample Format : dsf=',num2str(dsf)])
end
if strcmp(varargin{cargin},'SegyHeader')
cargin=cargin+1;
SegyHeader=varargin{cargin};
SegymatVerbose(['USING LOADED SEGYHEADER'])
end
cargin=cargin+1;
end
% SKIP DATA SEEMS OUTDATED, COMMENTING OUT 2003-10-24
%if exist('SkipData')==0,
% SkipData=0; % [0] READ ONLY HEADER VALUES, [1] READ IN ALL DATA
%end%%
%
%if SkipData==1, SegymatVerbose(['Not reading data - headers only']), end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% BINARY HEADERS
if isempty(SegyHeader)==1,
SegyHeader=GetSegyHeader(segyid);
else
SegymatVerbose([mfilename,' - Using supplied SegyHeader'])
end
% APPLY CHANGES TO SEGY HEADER IF NEEDE
if isempty(revision)==0,
SegyHeader.SegyFormatRevisionNumber=revision;
SegymatVerbose([mfilename,' - Manually set SEG-Y revision to ',num2str(revision)])
end
if isempty(dsf)==0,
SegyHeader.DataSampleFormat=dsf;
end
% JUST SOME INFORMATION TO WRITE TO SCREEN :
Revision=SegyHeader.SegyFormatRevisionNumber;
if Revision>0, Revision=1; end
FormatName=SegyHeader.Rev(Revision+1).DataSampleFormat(SegyHeader.DataSampleFormat).name;
Format=SegyHeader.Rev(Revision+1).DataSampleFormat(SegyHeader.DataSampleFormat).format;
BPS=SegyHeader.Rev(Revision+1).DataSampleFormat(SegyHeader.DataSampleFormat).bps;
txt=['SegyRevision ',sprintf('%0.4g',Revision),', ',FormatName,'(',num2str(SegyHeader.DataSampleFormat),')'];
ns=SegyHeader.ns;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% READ TEXTURAL FILE HEADER EXTENSION IF NEEDED
%if SegyHeader.NumberOfExtTextualHeaders~=0
% SegymatVerbose(['---------------------------------------------------'])
% SegymatVerbose(['extendeD textual file headers are not supported yet'])
% SegymatVerbose(['They are simply skipped'])
% SegymatVerbose(['---------------------------------------------------'])
%end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% READ DATA
%Segy=fread(segyid,4000,'float32');
fseek(segyid,0,'eof'); DataEnd=ftell(segyid);
DataStart=3600+3200*SegyHeader.NumberOfExtTextualHeaders;
fseek(segyid,DataStart,'bof'); % Go to the beginning of the file
ntraces=(DataEnd-DataStart)./(240+(SegyHeader.ns)*(BPS/8));
SegymatVerbose(['Number of Samples Per Trace=',num2str(SegyHeader.ns)])
SegymatVerbose(['Number of Traces=',num2str(ntraces)])
% Set Format :
Revision=SegyHeader.SegyFormatRevisionNumber;
if Revision>0, Revision=1; end
Format=SegyHeader.Rev(Revision+1).DataSampleFormat(SegyHeader.DataSampleFormat).format;
bitpersample=SegyHeader.Rev(Revision+1).DataSampleFormat(SegyHeader.DataSampleFormat).bps;
bytepersample=bitpersample/8;
ntraceheader=240/bytepersample;
Data=fread(segyid,[ns+ntraceheader ntraces],Format);
Data=Data([ntraceheader+1:1:ns+ntraceheader],:);
%SegymatVerbose(['Now=',num2str(ftell(segyid)),' END=',num2str(DataEnd)])
% THE FOLLOWING DOES NOT WORK FOR OCTAVE (uint32)
if (strcmp(Format,'uint32')==1), % IBM FLOATING POINT
% CONVERT FROM FLOATING POINT
verbose=1;
if verbose>1, SegymatVerbose([mfilename,'Converting from IBM, DataFormat :',SegyHeader.DataFormat]); end
Data=ibm2num(uint32(Data));
end;
existJump=1-isempty(jump);
existHeader=1-isempty(header);
existTmin=1-isempty(tmin);
existTmax=1-isempty(tmax);
if existJump
usetraces=[jump:jump:ntraces];
ntraces=length(usetraces);
Data=Data(:,usetraces);
end
if (existTmin==1)&(existTmax==1)
SegymatVerbose('TRANGE')
% NEXT LINE SHOULD CONSIDER THAT ns in Trace and Segy Header could vary !!!
origtrange=[1:1:SegyHeader.ns].*SegyHeader.dt.*1e-6;
gooddata=find(origtrange>tmin & origtrange<tmax);
Data=Data(gooddata,:);
end
|
github
|
Abakumov/MLIB-master
|
progress_txt.m
|
.m
|
MLIB-master/OTHER/SegyMAT/progress_txt.m
| 834 |
utf_8
|
ada36980089eab080dcd9448c144cd14
|
% progress_txt : console based progress bar
%
% Ex1 :
% for i=1:10000;
% progress_txt(i,10000,'Ciao');
% end
%
% Ex1 :
%
% for i=1:10;
% for j=1:10;
% for k=1:10;
% progress_txt([i j k],[10 100 1000],'i','j','k');
% end
% end
% end
%
% TMH/2005, [email protected]
%
function progress_txt(i,max,varargin);
if nargin==0
help progress_txt
return;
end
ncols=length(i);
%
nchar=45;
%
pc=i./max;
% clear command window
clc;
for m=1:ncols
try
txt=varargin{m};
catch
txt='';
end
char_prog='';
for j=1:nchar
if j<=(pc(m)*nchar);
char_prog=[char_prog,'#'];
else
char_prog=[char_prog,'_'];
end
end
disp(sprintf('%10s %s %3.1f%% %d/%d',txt,char_prog,100*pc(m),i(m),max(m)))
end
|
github
|
Abakumov/MLIB-master
|
Su2Segy.m
|
.m
|
MLIB-master/OTHER/SegyMAT/Su2Segy.m
| 1,073 |
utf_8
|
582a3ccd145296e692e07eeb6aaf25f5
|
% SU2Segy : Converts SEGY file to SU format
%
% (C) 2001-2004, Thomas Mejer Hansen, [email protected]/[email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
%
%
%
function SU2Segy(filename,varargin);
[Data,SegyTraceHeaders,SegyHeader,HeaderInfo]=ReadSu(filename,varargin);
WriteSegyStructure([filename,'.segy'],SegyHeader,SegyTraceHeaders,Data);%
|
github
|
Abakumov/MLIB-master
|
WriteSu.m
|
.m
|
MLIB-master/OTHER/SegyMAT/WriteSu.m
| 3,318 |
utf_8
|
bcf7d12eaefdc63bbfa4dd8a59600ba6
|
% WriteSu : writes data to disk using SEGY REV 2 standard.
%
% EX
% WriteSu('datacube.su',data,'dt',.004,'Inline3D',Inline,'Crossline3D',Crossline,'cdpX',X,'cdpY',Y);
%
% to use a specific SEG revision use :
% WriteSu('test.su',seisdata,'revision',0); % SEG-Y Revision 0
% WriteSu('test.su',seisdata,'revision',1); % SEG-Y Revision 1
%
% to use a specific Data Sampling Format use :
% WriteSu('test.su',seisdata,'dsf',1); % IBM FLAOTING POINT
%
% Forice Revision 1 and IEEE Floating point :
% WriteSu('test.su',seisdata,'dsf',5,'revision',1);
%
%
% (C) 2001-2004, Thomas Mejer Hansen, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
%
function WriteSu(filename,data,varargin);
[ns,ntraces]=size(data);
if exist('dt')~=1
dt=0.004;
SegymatVerbose([mfilename,' - No dt set. Using dt=',num2str(dt)])
end
for i=1:2:length(varargin)
var=varargin{i};
val=varargin{i+1};
eval([var,'=[',num2str(val),'];']);
end
SegyHeader.SegyFormatRevisionNumber=100;
SegyHeader.DataSampleFormat=5;
SegyHeader.Rev=GetSegyHeaderBasics;
% UNCOMMENT THE FOLLOWING TWO LINES TO USE REVISION 1 (2002)
%SegyHeader.SegyFormatRevisionNumber=100; % 2002 SEG Y STYLE
%SegyHeader.DataSampleFormat=2; % '1'->4-byte IBM floating point
% '2'->4-byte two's complement integer
% '3'->2-byte two's complement integer
% '5'->4-byte IEEE floating point (default)
% '8'->1-byte two's complement integer
% UNCOMMENT THE FOLLOWING TWO LINES TO USE REVISION 0 (1975)
%SegyHeader.SegyFormatRevisionNumber=0; % 1975 SEoG Y STYLE
%SegyHeader.DataSampleFormat=1; % '1'->4-byte IBM Floating Point
% OPEN SEGY FILE HANDLE
segyid = fopen(filename,'w');
% segyid = fopen(filename,'w','b'); % BIG ENDIAN
SegyTraceHeader=InitSegyTraceHeader(ns,dt*1e+6);
for i=1:ntraces;
if (i/100)==round(i/100),SegymatVerbose(['writing trace ',num2str(i),' of ',num2str(ntraces)],1),end
% Basic TraceHeader information
%SegyTraceHeader.ns=ns;
%SegyTraceHeader.dt=dt.*1e+6;
% Update TraceHeader information if available
if exist('cdpX')==1,SegyTraceHeader.cdpX = cdpX(i);end
if exist('offset')==1,SegyTraceHeader.offset = offset(i);end
if exist('cdpY')==1,SegyTraceHeader.cdpY = cdpY(i);end
if exist('Inline3D')==1,SegyTraceHeader.Inline3D = Inline3D(i);end
if exist('Crossline3D')==1,SegyTraceHeader.Crossline3D=Crossline3D(i);end
% Write the Trace
PutSegyTrace(segyid,data(:,i),SegyTraceHeader,SegyHeader);
end
% CLOSE SEGY FILE HANDLE
fclose(segyid);
|
github
|
Abakumov/MLIB-master
|
GetSegyHeader.m
|
.m
|
MLIB-master/OTHER/SegyMAT/GetSegyHeader.m
| 7,593 |
utf_8
|
9562256cd4ad8b52b8159e7efa06f86a
|
% GetSegyHeader : Reads the segyheader of a SEGY Y formatted file
%
% Call :
% [SegyHeader]=GetSegyHeader(segyid);
%
% segyid can be a filehandle or a filename
%
%
% (C) 2001-2004 Thomas Mejer Hansen, [email protected]/[email protected]
%
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
%
function [SegyHeader]=GetSegyHeader(segyid,varargin);
mfilename='GetSegyHeader';
SegymatVerbose([mfilename,' : Start'],90);
ninput=nargin;
% NEXT TWO LINES TO ENUSRE THAT VARARGIN CAN BE PASSED TO FUNCTION
if ninput==2
% CALL USING VARARGIN
ninput=1+length(varargin{1});
varargin=varargin{1};
else
% DIRECT CALL
ninput=length(varargin);
end
% TRANSFORM VARARGING INTO PARAMETERS
cargin=1;
while (cargin<ninput)
% ENDIAN FORMAT
endian='ieee-be'; % Big Endian is default
if strcmp(varargin{cargin},'endian')
cargin=cargin+1;
eval(['endian_tight=varargin{cargin};'])
if endian_tight=='l',
SegymatVerbose(['USING LITTLE ENDIAN TYPE'])
endian='ieee-le';
else
SegymatVerbose(['USING BIG ENDIAN TYPE'])
end
end
if strcmp(varargin{cargin},'revision')
cargin=cargin+1;
eval(['revision=',num2str(varargin{cargin}),';']);
SegymatVerbose(['USING REVISION : rev=',num2str(revision)])
end
if strcmp(varargin{cargin},'dsf')
cargin=cargin+1;
eval(['dsf=',num2str(varargin{cargin}),';']);
SegymatVerbose(['USING Data Sample Format : dsf=',num2str(dsf)])
end
if strcmp(varargin{cargin},'SkipData')
cargin=cargin+1;
eval(['SkipData=',num2str(varargin{cargin}),';']);
SegymatVerbose(['SKIPPING DATA - READING ONLY HEADERS'])
end
cargin=cargin+1;
end
if ischar(segyid)
% if segyid is a string it is interpreted as a filename
%
segyid = fopen(segyid,'r','b'); % ALL DISK FILES ARE IN BIG
% ENDIAN FORMAT, ACCORDING TO SEG
% Y rev 1
end
% Basic Segy Header Information.
SegyHeader.Rev=GetSegyHeaderBasics;
fseek(segyid,0,'bof');
SegyHeader.TextualFileHeader=fread(segyid,3200,'uchar'); % 3200
SegyHeader.Job=fread(segyid,1,'int32'); % 3204
SegyHeader.Line=fread(segyid,1,'int32'); % 3208
SegyHeader.Reel=fread(segyid,1,'int32'); % 3212
SegyHeader.DataTracePerEnsemble=fread(segyid,1,'int16'); % 3214
SegyHeader.AuxiliaryTracePerEnsemble=fread(segyid,1,'uint16'); % 3216
SegyHeader.dt=fread(segyid,1,'uint16'); % 3218
SegyHeader.dtOrig=fread(segyid,1,'uint16'); % 3220
SegyHeader.ns=fread(segyid,1,'uint16'); % 3222
SegyHeader.nsOrig=fread(segyid,1,'uint16'); % 3224
SegyHeader.DataSampleFormat=fread(segyid,1,'int16'); % 3226
SegyHeader.EnsembleFold=fread(segyid,1,'int16');
SegyHeader.TraceSorting=fread(segyid,1,'int16'); % 3228
SegyHeader.VerticalSumCode=fread(segyid,1,'int16'); % 3230
SegyHeader.SweepFrequencyStart=fread(segyid,1,'int16'); % 3232
SegyHeader.SweepFrequencyEnd=fread(segyid,1,'int16'); % 3234
SegyHeader.SweepLength=fread(segyid,1,'int16'); % 3236
SegyHeader.SweepType=fread(segyid,1,'int16'); % 3238
SegyHeader.SweepChannel=fread(segyid,1,'int16'); % 3240
SegyHeader.SweepTaperlengthStart=fread(segyid,1,'int16'); % 3242
SegyHeader.SweepTaperLengthEnd=fread(segyid,1,'int16'); % 3244
SegyHeader.TaperType=fread(segyid,1,'int16'); % 3246
SegyHeader.CorrelatedDataTraces=fread(segyid,1,'int16'); % 3248
SegyHeader.BinaryGain=fread(segyid,1,'int16'); % 3250
SegyHeader.AmplitudeRecoveryMethod=fread(segyid,1,'int16'); % 3252
SegyHeader.MeasurementSystem=fread(segyid,1,'int16'); % 3254
SegyHeader.ImpulseSignalPolarity=fread(segyid,1,'int16'); % 3256
SegyHeader.VibratoryPolarityCode=fread(segyid,1,'int16'); % 3258
% 3261-3500 UNASSIGNED (as 120*2byte integer)
SegyHeader.Unassigned1=fread(segyid,120,'int16'); % 3260
% fseek(segyid,3500,'bof');
SegyHeader.SegyFormatRevisionNumber=fread(segyid,1,'uint16'); % 3500
SegyHeader.FixedLengthTraceFlag=fread(segyid,1,'integer*2'); % 3502
SegyHeader.NumberOfExtTextualHeaders=fread(segyid,1,'uint16'); % 3504
% 3506-3600 UNASSIGNED (as 47*2byte integer = 94 byte)
SegyHeader.Unassigned2=fread(segyid,47,'int16'); % 3506
% READ TEXTURAL FILE HEADER EXTENSION IF NEEDED
%fseek(segyid,3600,'bof');
if (SegyHeader.NumberOfExtTextualHeaders>0),
SegymatVerbose(['---------------------------------------------------'])
SegymatVerbose(['extended textual file headers are implemented '])
SegymatVerbose(['but have not been tested, since I([email protected]) '])
SegymatVerbose(['have had no access to SEGY REV-1 files formatted '])
SegymatVerbose(['like this. Please contact me if you have such a '])
SegymatVerbose(['file to share '])
SegymatVerbose(['---------------------------------------------------'])
txt=sprintf('%d Extended Textual File Headers',SegyHeader.NumberOfExtTextualHeaders);
SegymatVerbose(txt);
nChars=3200*SegyHeader.NumberOfExtTextualHeaders;
SegyHeader.ExtTextualHeaders=fread(segyid,nChars,'schar'); % 3600
else
SegymatVerbose('NO extended textual file headers');
end
SegyHeader.time=[1:1:SegyHeader.ns].*SegyHeader.dt./1e+6;
Revision=SegyHeader.SegyFormatRevisionNumber;
if Revision>0, Revision=1; end
if (SegyHeader.DataSampleFormat>length(SegyHeader.Rev(Revision+1).DataSampleFormat));
SegymatVerbose([mfilename,' : WARNING : YOU HAVE SELECTED (OR THE FILE IS FORMATTED SUCH THAT) A DATASAMPLE FORMAT THAT IS NOT DEFINED. \nREMEBER IEEE IS NOT SPECIFIED IN THE SEGY REV0 STANDARD !'])
if (Revision==0)
SegymatVerbose([mfilename,' : TRYING TO USE REVISION 1 AS OPPOSED TO REVISION 0'])
Revision=1;
if (SegyHeader.DataSampleFormat>length(SegyHeader.Rev(Revision+1).DataSampleFormat));
SegymatVerbose([mfilename,' : FATAL ERROR : STILL THE DATASAMPLE FORMAT IS NOT SUPPRTED - EXITING (Report error to [email protected])'])
else
SegymatVerbose([mfilename,' : APPARENT SUCCES CHANING FROM Revision 0 to 1 - Continuing'])
SegyHeader.SegyFormatRevisionNumber=1; % FORCING REVISION TO BE 1 !!!
end
end
end
try
Format=SegyHeader.Rev(Revision+1).DataSampleFormat(SegyHeader.DataSampleFormat).name;
SegymatVerbose([mfilename,' : SegyRevision ',sprintf('%0.4g',Revision),', ',Format,'(',num2str(SegyHeader.DataSampleFormat),')'])
catch
end
if ischar(segyid)
fclose(segyid);
end
SegymatVerbose([mfilename,' : End'],90);
|
github
|
Abakumov/MLIB-master
|
InitSegyTraceHeader.m
|
.m
|
MLIB-master/OTHER/SegyMAT/InitSegyTraceHeader.m
| 4,840 |
utf_8
|
72537f1c86a8642a67d9ae6b74ec91c9
|
% InitSegyTraceHeaders : returns an empty SegyTraceHeader structure
%
% EX:
% SegyTraceHeader=InitSegyTraceHeader(ns,dt);
%
%
% (C) 2001-2004, Thomas Mejer Hansen, [email protected]/[email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
%
function SegyTraceHeader=InitSegyTraceHeader(ns,dt);
SegyTraceHeader=[];
if exist('ns')==0,
SegymatVerbose([mfilename,' : ns not set !! returning'],0)
return
end
if exist('dt')==0,
dt=4000;
SegymatVerbose([mfilename,' : dt not set. using dt=',num2str(dt)],0)
end
NA=0;
da=clock;
DayOfYear=datenum(0,da(2),da(3));
SegyTraceHeader.TraceSequenceLine=NA;
SegyTraceHeader.TraceSequenceFile=NA;
SegyTraceHeader.FieldRecord=NA;
SegyTraceHeader.TraceNumber=NA;;
SegyTraceHeader.EnergySourcePoint=NA;
SegyTraceHeader.cdp=NA;
SegyTraceHeader.cdpTrace=NA;
SegyTraceHeader.TraceIdenitifactionCode=NA;
SegyTraceHeader.NSummedTraces=NA;
SegyTraceHeader.NStackedTraces=NA;
SegyTraceHeader.DataUse=NA;
SegyTraceHeader.offset=NA;
SegyTraceHeader.ReceiverGroupElevation=NA;
SegyTraceHeader.SourceSurfaceElevation=NA;
SegyTraceHeader.SourceDepth=NA;
SegyTraceHeader.ReceiverDatumElevation=NA;
SegyTraceHeader.SourceDatumElevation=NA;
SegyTraceHeader.SourceWaterDepth=NA;
SegyTraceHeader.GroupWaterDepth=NA;
SegyTraceHeader.ElevationScalar=NA;
SegyTraceHeader.SourceGroupScalar=NA;
SegyTraceHeader.SourceX=NA;
SegyTraceHeader.SourceY=NA;
SegyTraceHeader.GroupX=NA;
SegyTraceHeader.GroupY=NA;
SegyTraceHeader.CoordinateUnits=NA;
SegyTraceHeader.WeatheringVelocity=NA;
SegyTraceHeader.SubWeatheringVelocity=NA;
SegyTraceHeader.SourceUpholeTime=NA;
SegyTraceHeader.GroupUpholeTime=NA;
SegyTraceHeader.SourceStaticCorrection=NA;
SegyTraceHeader.GroupStaticCorrection=NA;
SegyTraceHeader.TotalStaticApplied=NA;
SegyTraceHeader.LagTimeA=NA;
SegyTraceHeader.LagTimeB=NA;
SegyTraceHeader.DelayRecordingTime=NA;
SegyTraceHeader.MuteTimeStart=NA;
SegyTraceHeader.MuteTimeEND=NA;
SegyTraceHeader.ns=ns;
SegyTraceHeader.dt=dt;
SegyTraceHeader.GainType=NA;
SegyTraceHeader.InstrumentGainConstant=NA;
SegyTraceHeader.InstrumentInitialGain=NA;
SegyTraceHeader.Correlated=NA;
SegyTraceHeader.SweepFrequenceStart=NA;
SegyTraceHeader.SweepFrequenceEnd=NA;
SegyTraceHeader.SweepLength=NA;
SegyTraceHeader.SweepType=NA;
SegyTraceHeader.SweepTraceTaperLengthStart=NA;
SegyTraceHeader.SweepTraceTaperLengthEnd=NA;
SegyTraceHeader.TaperType=NA;
SegyTraceHeader.AliasFilterFrequency=NA;
SegyTraceHeader.AliasFilterSlope=NA;
SegyTraceHeader.NotchFilterFrequency=NA;
SegyTraceHeader.NotchFilterSlope=NA;
SegyTraceHeader.LowCutFrequency=NA;
SegyTraceHeader.HighCutFrequency=NA;
SegyTraceHeader.LowCutSlope=NA;
SegyTraceHeader.HighCutSlope=NA;
SegyTraceHeader.YearDataRecorded=da(1);
SegyTraceHeader.DayOfYear=DayOfYear;
SegyTraceHeader.HourOfDay=da(4);
SegyTraceHeader.MinuteOfHour=da(5);
SegyTraceHeader.SecondOfMinute=round(da(6));
SegyTraceHeader.TimeBaseCode=NA;
SegyTraceHeader.TraceWeightningFactor=NA;
SegyTraceHeader.GeophoneGroupNumberRoll1=NA;
SegyTraceHeader.GeophoneGroupNumberFirstTraceOrigField=NA;
SegyTraceHeader.GeophoneGroupNumberLastTraceOrigField=NA;
SegyTraceHeader.GapSize=NA;
SegyTraceHeader.OverTravel=NA;
SegyTraceHeader.cdpX=NA;
SegyTraceHeader.cdpY=NA;
SegyTraceHeader.Inline3D=NA;
SegyTraceHeader.Crossline3D=NA;
SegyTraceHeader.ShotPoint=NA;
SegyTraceHeader.ShotPointScalar=NA;
SegyTraceHeader.TraceValueMeasurementUnit=NA;
SegyTraceHeader.TransductionConstantMantissa=NA;
SegyTraceHeader.TransductionConstantPower=NA;
SegyTraceHeader.TransductionUnit=NA;
SegyTraceHeader.TraceIdentifier=NA;
SegyTraceHeader.ScalarTraceHeader=NA;
SegyTraceHeader.SourceType=NA;
SegyTraceHeader.SourceEnergyDirectionMantissa=NA;
SegyTraceHeader.SourceEnergyDirectionExponent=NA;
SegyTraceHeader.SourceMeasurementMantissa=NA;
SegyTraceHeader.SourceMeasurementExponent=NA;
SegyTraceHeader.SourceMeasurementUnit=NA;
SegyTraceHeader.UnassignedInt1=NA;
SegyTraceHeader.UnassignedInt2=NA;
|
github
|
Abakumov/MLIB-master
|
GetSegyTraceHeader.m
|
.m
|
MLIB-master/OTHER/SegyMAT/GetSegyTraceHeader.m
| 8,830 |
utf_8
|
330af92104ce4a2df035bef2bc573e7f
|
% GetSegyTraceHeader : Reads a seg y trace, data and header
%
% [SegyTraceHeader]=GetSegyTraceHeader(segyid,TraceStart,DataFormat,ns);
%
%
% (C) 2001-2004 Thomas Mejer Hansen, [email protected]
%
% Revisions:
% 07/2008 Kristian Stormark (<[email protected]>) : Reduce the
% number of discoperations causing a significant speed up
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
%
function [SegyTraceHeader]=GetSegyTraceHeader(segyid,TraceStart,DataFormat,ns,SegyTraceHeader);
if exist('DataFormat')==0, DataFormat='float32'; end
if exist('TraceStart')==0, TraceStart=ftell(segyid); end
if exist('SegyTraceHeader')
if isempty('SegyTraceHeader');
clear SegyTraceHeader;
end
end
fseek(segyid,TraceStart,'bof');
% GET POSITION FOR EASY LATER LOCALIZATION
SegyTraceHeader.SegyMAT_TraceStart = ftell(segyid);
chunk = fread(segyid,7,'int32');
SegyTraceHeader.TraceSequenceLine = chunk(1); % 0
SegyTraceHeader.TraceSequenceFile = chunk(2); % 4
SegyTraceHeader.FieldRecord = chunk(3); % 8
SegyTraceHeader.TraceNumber = chunk(4); % 12
SegyTraceHeader.EnergySourcePoint = chunk(5); % 16
SegyTraceHeader.cdp = chunk(6); % 20
SegyTraceHeader.cdpTrace = chunk(7); % 24
chunk = fread(segyid,4,'int16');
SegyTraceHeader.TraceIdenitifactionCode = chunk(1); % 28
SegyTraceHeader.NSummedTraces = chunk(2); % 30
SegyTraceHeader.NStackedTraces = chunk(3); % 32
SegyTraceHeader.DataUse = chunk(4); % 34
chunk = fread(segyid,8,'int32');
SegyTraceHeader.offset = chunk(1); %36
SegyTraceHeader.ReceiverGroupElevation = chunk(2); %40
SegyTraceHeader.SourceSurfaceElevation = chunk(3); %44
SegyTraceHeader.SourceDepth = chunk(4); %48
SegyTraceHeader.ReceiverDatumElevation = chunk(5); %52
SegyTraceHeader.SourceDatumElevation = chunk(6); %56
SegyTraceHeader.SourceWaterDepth = chunk(7); %60
SegyTraceHeader.GroupWaterDepth = chunk(8); %64
chunk = fread(segyid,2,'int16');
SegyTraceHeader.ElevationScalar = chunk(1); %68
% Multiply/divide next number for following 4 values
SegyTraceHeader.SourceGroupScalar = chunk(2); %70
chunk = fread(segyid,4,'int32');
SegyTraceHeader.SourceX = chunk(1); %72
SegyTraceHeader.SourceY = chunk(2); %76
SegyTraceHeader.GroupX = chunk(3); %80
SegyTraceHeader.GroupY = chunk(4); %84
chunk = fread(segyid,13,'int16');
SegyTraceHeader.CoordinateUnits = chunk(1); %88
SegyTraceHeader.WeatheringVelocity = chunk(2); %90
SegyTraceHeader.SubWeatheringVelocity = chunk(3); %92
SegyTraceHeader.SourceUpholeTime = chunk(4); %94
SegyTraceHeader.GroupUpholeTime = chunk(5); %96
SegyTraceHeader.SourceStaticCorrection = chunk(6); %98
SegyTraceHeader.GroupStaticCorrection = chunk(7); %100
SegyTraceHeader.TotalStaticApplied = chunk(8); %102
SegyTraceHeader.LagTimeA = chunk(9); %104
SegyTraceHeader.LagTimeB = chunk(10); %106
SegyTraceHeader.DelayRecordingTime = chunk(11); %108
SegyTraceHeader.MuteTimeStart = chunk(12); %110
SegyTraceHeader.MuteTimeEND = chunk(13); %112
chunk = fread(segyid,2,'uint16');
SegyTraceHeader.ns = chunk(1); %114
SegyTraceHeader.dt = chunk(2); %116
chunk = fread(segyid,31,'int16');
SegyTraceHeader.GainType = chunk(1); %118
SegyTraceHeader.InstrumentGainConstant = chunk(2); %120
SegyTraceHeader.InstrumentInitialGain = chunk(3); %%122
SegyTraceHeader.Correlated = chunk(4); %124
SegyTraceHeader.SweepFrequenceStart = chunk(5); %126
SegyTraceHeader.SweepFrequenceEnd = chunk(6); %128
SegyTraceHeader.SweepLength = chunk(7); %130
SegyTraceHeader.SweepType = chunk(8); %132
SegyTraceHeader.SweepTraceTaperLengthStart = chunk(9); %134
SegyTraceHeader.SweepTraceTaperLengthEnd = chunk(10); %136
SegyTraceHeader.TaperType = chunk(11); %138
SegyTraceHeader.AliasFilterFrequency = chunk(12); %140
SegyTraceHeader.AliasFilterSlope = chunk(13); %142
SegyTraceHeader.NotchFilterFrequency = chunk(14); %144
SegyTraceHeader.NotchFilterSlope = chunk(15); %146
SegyTraceHeader.LowCutFrequency = chunk(16); %148
SegyTraceHeader.HighCutFrequency = chunk(17); %150
SegyTraceHeader.LowCutSlope = chunk(18); %152
SegyTraceHeader.HighCutSlope = chunk(19); %154
SegyTraceHeader.YearDataRecorded = chunk(20); %156
SegyTraceHeader.DayOfYear = chunk(21); %158
SegyTraceHeader.HourOfDay = chunk(22); %160
SegyTraceHeader.MinuteOfHour = chunk(23); %162
SegyTraceHeader.SecondOfMinute = chunk(24); %164
SegyTraceHeader.TimeBaseCode = chunk(25); %166
if SegyTraceHeader.TimeBaseCode==1, SegyTraceHeader.TimeBaseCodeText='Local';
elseif SegyTraceHeader.TimeBaseCode==2, SegyTraceHeader.TimeBaseCodeText='GMT';
elseif SegyTraceHeader.TimeBaseCode==3, SegyTraceHeader.TimeBaseCodeText='Other';
elseif SegyTraceHeader.TimeBaseCode==4, SegyTraceHeader.TimeBaseCodeText='UTC';
else SegyTraceHeader.TimeBaseCodeText=''; end
SegyTraceHeader.TraceWeightningFactor = chunk(26); %168
SegyTraceHeader.GeophoneGroupNumberRoll1 = chunk(27); %170
SegyTraceHeader.GeophoneGroupNumberFirstTraceOrigField = chunk(28); %172
SegyTraceHeader.GeophoneGroupNumberLastTraceOrigField = chunk(29); %174
SegyTraceHeader.GapSize = chunk(30); %176
SegyTraceHeader.OverTravel = chunk(31); %178
chunk = fread(segyid,5,'int32');
SegyTraceHeader.cdpX = chunk(1); %180
SegyTraceHeader.cdpY = chunk(2); %184
SegyTraceHeader.Inline3D = chunk(3); %188
SegyTraceHeader.Crossline3D = chunk(4); %192
SegyTraceHeader.ShotPoint = chunk(5); %196
SegyTraceHeader.ShotPointScalar=fread(segyid,1,'int16'); %200
SegyTraceHeader.TraceValueMeasurementUnit=fread(segyid,1,'int16'); %202
if SegyTraceHeader.TraceValueMeasurementUnit==-1, SegyTraceHeader.TraceValueMeasurementUnitText='Other';
elseif SegyTraceHeader.TraceValueMeasurementUnit==0, SegyTraceHeader.TraceValueMeasurementUnitText='Unknown';
elseif SegyTraceHeader.TraceValueMeasurementUnit==1, SegyTraceHeader.TraceValueMeasurementUnitText='Pascal (Pa)';
elseif SegyTraceHeader.TraceValueMeasurementUnit==2, SegyTraceHeader.TraceValueMeasurementUnitText='Volts (v)';
elseif SegyTraceHeader.TraceValueMeasurementUnit==3, SegyTraceHeader.TraceValueMeasurementUnitText='Millivolts (v)';
elseif SegyTraceHeader.TraceValueMeasurementUnit==4, SegyTraceHeader.TraceValueMeasurementUnitText='Amperes (A)';
elseif SegyTraceHeader.TraceValueMeasurementUnit==5, SegyTraceHeader.TraceValueMeasurementUnitText='Meters (m)';
elseif SegyTraceHeader.TraceValueMeasurementUnit==6, SegyTraceHeader.TraceValueMeasurementUnitText='Meters Per Second (m/s)';
elseif SegyTraceHeader.TraceValueMeasurementUnit==7, SegyTraceHeader.TraceValueMeasurementUnitText='Meters Per Second squared (m/&s2)Other';
elseif SegyTraceHeader.TraceValueMeasurementUnit==8, SegyTraceHeader.TraceValueMeasurementUnitText='Newton (N)';
elseif SegyTraceHeader.TraceValueMeasurementUnit==8, SegyTraceHeader.TraceValueMeasurementUnitText='Watt (W)';
else SegyTraceHeader.TraceValueMeasurementUnitText='Undefined'; end
SegyTraceHeader.TransductionConstantMantissa=fread(segyid,1,'int32'); %204
chunk = fread(segyid,5,'int16');
SegyTraceHeader.TransductionConstantPower = chunk(1);%208
SegyTraceHeader.TransductionUnit = chunk(2); %210
SegyTraceHeader.TraceIdentifier = chunk(3); %212
SegyTraceHeader.ScalarTraceHeader = chunk(4); %214
SegyTraceHeader.SourceType = chunk(5); %216
SegyTraceHeader.SourceEnergyDirectionMantissa=fread(segyid,1,'int32'); %218
SegyTraceHeader.SourceEnergyDirectionExponent=fread(segyid,1,'int16'); %222
SegyTraceHeader.SourceMeasurementMantissa=fread(segyid,1,'int32'); %224
chunk = fread(segyid,2,'int16');
SegyTraceHeader.SourceMeasurementExponent = chunk(1); %228
SegyTraceHeader.SourceMeasurementUnit = chunk(2); %230
chunk = fread(segyid,2,'int32');
SegyTraceHeader.UnassignedInt1 = chunk(1); %232
SegyTraceHeader.UnassignedInt2 = chunk(2); %236
if exist('ns')==0,
ns=SegyTraceHeader.ns;
end
% GO TO POSITION OF DATA
fseek(segyid,TraceStart+240,'bof');
SegyTraceHeader.SegyMAT_TraceDataStart = ftell(segyid);
|
github
|
Abakumov/MLIB-master
|
GetSegyTraceHeaderInfo.m
|
.m
|
MLIB-master/OTHER/SegyMAT/GetSegyTraceHeaderInfo.m
| 1,279 |
utf_8
|
4bb8478252c51abec3bd32e1500d4ab2
|
% GetSegyTraceHeaderInfo : Returns a array of a SEGY Y TraceHeader value
%
% Call :
% [value]=GetSegyHeaderInfo(SegyTraceHeaders,header)
%
% header is a header value like 'cdp','dt','TraceNumber'
%
%
% (C) 2001-2004, Thomas Mejer Hansen, [email protected]/[email protected]
%
%
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
%
function [value]=GetSegyTraceHeaderInfo(SegyTraceHeaders,header)
try
value=[SegyTraceHeaders.(header)];
catch
SegymatVerbose(['Could not get ',header,' header information from supplied SegyTraceHeaders']);
end
|
github
|
Abakumov/MLIB-master
|
ebcdic2ascii.m
|
.m
|
MLIB-master/OTHER/SegyMAT/ebcdic2ascii.m
| 3,933 |
utf_8
|
63cbc443cb05b624d00edc3f02b957d5
|
% ebcdic2ascii : Converts EBCDIC formatted text to ASCII formatted text
%
% CALL : ascii=ebcdic2ascii(ebcdic);
%
% ebcdic : Array on unsigned integers
% ascii : Array on unsigned integers
%
% (C) 2002-2004, Thomas Mejer Hansen, [email protected]/[email protected]
%
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
%
function ascii=ebcdic2ascii(ebcdic)
ebcdic_arr=[
'00';'01';'02';'03';'04';'05';'06';'07';'08';'09';
'0A';'0B';'0C';'0D';'0E';'0F';'10';'11';'12';'13';
'14';'15';'16';'17';'18';'19';'1A';'1B';'1C';'1D';
'1E';'1F';'20';'21';'22';'23';'24';'25';'26';'27';
'28';'29';'2A';'2B';'2C';'2D';'2E';'2F';'30';'31';
'32';'33';'34';'35';'36';'37';'38';'39';'3A';'3B';
'3C';'3D';'3E';'3F';'40';'4A';'4B';'4C';'4D';'4E';
'4F';'50';'5A';'5B';'5C';'5D';'5E';'5F';'60';'61';
'6A';'6B';'6C';'6D';'6E';'6F';'79';'7A';'7B';'7C';
'7D';'7E';'7F';'81';'82';'83';'84';'85';'86';'87';
'88';'89';'91';'92';'93';'94';'95';'96';'97';'98';
'99';'A1';'A2';'A3';'A4';'A5';'A6';'A7';'A8';'A9';
'C0';'C1';'C2';'C3';'C4';'C5';'C6';'C7';'C8';'C9';
'D0';'D1';'D2';'D3';'D4';'D5';'D6';'D7';'D8';'D9';
'E0';'E2';'E3';'E4';'E5';'E6';'E7';'E8';'E9';'F0';
'F1';'F2';'F3';'F4';'F5';'F6';'F7';'F8';'F9';'FF';
'00';'01';'02';'03';'37';'2D';'2E';'2F';'2F';'16';
'05';'25';'0B';'0C';'0D';'10';'11';'12';'13';'3C';
'3D';'32';'26';'18';'3F';'27';'1C';'1D';'1D';'1E';
'1F';'07';'40';'5A';'7F';'7B';'5B';'6C';'50';'7D';
'4D';'5D';'5C';'4E';'6B';'60';'4B';'61';'F0';'F1';
'F2';'F3';'F4';'F5';'F6';'F7';'F8';'F9';'7A';'5E';
'4C';'7E';'6E';'6F';'7C';'00';'E0';'00';'00';'6D';
'79';'C0';'4F';'D0';'A1'];
ascii_arr=[
'00';'01';'02';'03';'9C';'09';'86';'7F';'97';'8D';
'8E';'0B';'0C';'0D';'0E';'0F';'10';'11';'12';'13';
'9D';'85';'08';'87';'18';'19';'92';'8F';'1C';'1D';
'1E';'1F';'80';'81';'82';'83';'84';'0A';'17';'1B';
'88';'89';'8A';'8B';'8C';'05';'06';'07';'90';'91';
'16';'93';'94';'95';'96';'04';'98';'99';'9A';'9B';
'14';'15';'9E';'1A';'20';'A2';'2E';'3C';'28';'2B';
'7C';'26';'21';'24';'2A';'29';'3B';'AC';'2D';'2F';
'A6';'2C';'25';'5F';'3E';'3F';'60';'3A';'23';'40';
'27';'3D';'22';'61';'62';'63';'64';'65';'66';'67';
'68';'69';'6A';'6B';'6C';'6D';'6E';'6F';'70';'71';
'72';'7E';'73';'74';'75';'76';'77';'78';'79';'7A';
'7B';'41';'42';'43';'44';'45';'46';'47';'48';'49';
'7D';'4A';'4B';'4C';'4D';'4E';'4F';'50';'51';'52';
'5C';'53';'54';'55';'56';'57';'58';'59';'5A';'30';
'31';'32';'33';'34';'35';'36';'37';'38';'39';'9F';
'00';'01';'02';'03';'04';'05';'06';'07';'07';'08';
'09';'0A';'0B';'0C';'0D';'10';'11';'12';'13';'14';
'15';'16';'17';'18';'1A';'1B';'1C';'1D';'1D';'1E';
'1F';'7F';'20';'21';'22';'23';'24';'25';'26';'27';
'28';'29';'2A';'2B';'2C';'2D';'2E';'2F';'30';'31';
'32';'33';'34';'35';'36';'37';'38';'39';'3A';'3B';
'3C';'3D';'3E';'3F';'40';'5B';'5C';'5D';'5E';'5F';
'60';'7B';'7C';'7D';'7E'
];
ascii_dec_array=hex2dec(ascii_arr);
ebcdic_dec_array=hex2dec(ebcdic_arr);
for i=1:length(ebcdic)
m=find(ebcdic_dec_array==ebcdic(i));
if length(m)>1,
m=m(1);
end
if length(m)==0,
ascii(i)=0;
else
ascii(i)=(ascii_dec_array(m));
end
end
|
github
|
Abakumov/MLIB-master
|
ReadSegy.m
|
.m
|
MLIB-master/OTHER/SegyMAT/ReadSegy.m
| 17,806 |
utf_8
|
a9dd85e406d08c604ae522b9bd99e144
|
% ReadSegy : Reads a SEG Y rev 1 formatted file
%
% Call :
% [Data,SegyTraceHeaders,SegyHeader]=ReadSegy(filename);
%
% To read time slice 0.5<t<5 :
% [Data,SegyTraceHeaders,SegyHeader]=ReadSegy(filename,'trange',.5,3);
% To read time trace number 100,110 and 150 :
% [Data,SegyTraceHeaders,SegyHeader]=ReadSegy(filename,'traces',[100 110 150]);
% Skip every 5th trace :
% [Data,SegyTraceHeaders,SegyHeader]=ReadSegy(filename,'jump',5);
% Read data in a CDP header range : 5000<cdp<5800 :
% (change cdp to any other valid TraceHeader value)
% [Data,SegyTraceHeaders,SegyHeader]=ReadSegy(filename,'minmax','cdp',5000,5800);
% Read only the header values (Data will return empty)
% [Data,SegyTraceHeaders,SegyHeader]=ReadSegy(filename,'SkipData',1);
%
% SEG-Y format revision number can be '0' (1975) or
% '100' (similar to '1') (2002).
% By default the SEG-Y format revision number is read in the
% binary header, but this can be overruled using :
% [Data,SegyTraceHeaders,SegyHeader]=ReadSegy(filename,'revision',0);
%
% Read using a specific Data Sample Format :
% Rev 0, IBM FLOATING POINT
% [Data,SegyTraceHeaders,SegyHeader]=ReadSegy(filename,'revision',0,'dsf',1);
% Rev 1, IEEE FLOATING POINT
% [Data,SegyTraceHeaders,SegyHeader]=ReadSegy(filename,'revision',1,'dsf',5);
%
% A SegyHeader can be forced on the SEG-Y file using :
% [Data,SegyTraceHeaders,SegyHeader]=ReadSegy(filename,'SegyHeader',SegyHeader);
% The SegyHeader can be obtain by GetSegyHeader(segyfilename), and
% then edited.
%
% To read using little endian :
% [Data,SegyTraceHeaders,SegyHeader]=ReadSegy(filename,'endian','l');
%
% Combine any combination of the above
% [Data,SegyTraceHeaders,SegyHeader]=ReadSegy(filename,'jump',1,'minmax','cdp',5300,5400);
%
%
% Plot the data using e.g.
% imagesc([SegyTraceHeaders.cdp],SegyHeader.time,Data);
% wiggle([SegyTraceHeaders.TraceNumber],SegyHeader.time,Data);
%
% (C) 2003-2004, Thomas Mejer Hansen, [email protected]
%
% Implemented using the syntax of the SEG-Y revised format :
% SEGY-Y rev 0, SEG-Y rev 1 as described in
% http://seg.org/publications/tech-stand/
%
% Extended Textual Header is not yet tested
% If you would like it implemented, please send me an SEGY file with
% that sort of information, as well as a description of the segy file
%
%
% (C) 2001-2004, Thomas Mejer Hansen, [email protected]/[email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
%
%
%
%
% 0.1 : INitial Release
% 0.2 : Added SkipData var, to skip reading of data.
% 0.3 : May 01, 2002
% Added ability to read in ever 'jump' traces.
% Added ability to read in time range.
% Added abiliy to read in header range (ex. mincdp to maxcdp).
%
% TODO : WHEN READING ONLY PART OF DATASET MAKE SURE TO ADJUST THE SEGY
% HEADER ACCORDINGLY !!!!!!
function [Data,SegyTraceHeaders,SegyHeader,HeaderInfo]=ReadSegy(filename,varargin);
if isoctave
doWaitBar=0; % [1] show progress bar gui
mfilename='ReadSegy';
else
doWaitBar=0;
mfilename='ReadSegy';
end
dsf=[];
revision=[];
endian_tight=[];
tmin=[];tmax=[];
headermin=[];headermax=[];header=[];
jump=[];
SkipData=[];
%endian='ieee-be'; % Big Endian is default
endian='ieee-le'; % little endian
SegymatVerbose([mfilename,' : reading ',filename])
if ~(exist(filename)==2'),
SegymatVerbose([mfilename,' : ', filename,' does not exist !'])
Data=[];SegyTraceHeaders=[];SegyHeader=[];HeaderInfo=[];
return
end
% IF ONLY 'filename', AND one outpuet HAS BEEN
% SPECIFIED AS IN/OUTPUT, THEN USE THE FAST
% ALGORITHM FOR READING.
if (nargin==1)&(nargout==1)
[Data]=ReadSegyFast(filename);
return
end
SegymatVerbose([mfilename,' - Checking Varargin'],90)
ninput=nargin;
% NEXT TWO LINES TO ENUSRE THAT VARARGIN CAN BE PASSED TO FUNCTION
if ninput==2
% CALL USING VARARGIN
ninput=1+length(varargin{1});
varargin=varargin{1};
else
% DIRECT CALL
ninput=length(varargin);
end
% TRANSFORM VARARGING INTO PARAMETERS
traces=[];
cargin=1;
while (cargin<ninput)
SegymatVerbose([mfilename,' - Converting varargin, ',num2str(cargin)],90)
if strcmp(varargin{cargin},'jump')
cargin=cargin+1;
eval(['jump=',num2str(varargin{cargin}),';']);
SegymatVerbose(['JUMP : Read only every ',num2str(jump),'th trace'])
end
if strcmp(varargin{cargin},'traces')
cargin=cargin+1;
traces=varargin{cargin};
SegymatVerbose(['TRACES : Read only every ',num2str(jump),'th trace'])
end
if strcmp(varargin{cargin},'minmax')
cargin=cargin+1;
eval(['header=''',varargin{cargin},''';']);
cargin=cargin+1;
eval(['headermin=',num2str(varargin{cargin}),';']);
cargin=cargin+1;
eval(['headermax=',num2str(varargin{cargin}),';']);
SegymatVerbose(['MIN MAX : Using header ',header,' from ',num2str(headermin),' to ',num2str(headermax)])
h=ReadSegyTraceHeaderValue(filename,'key',header);
minmax_traces=find(h>=headermin & h<=headermax);
if isempty(traces)
traces=minmax_traces;
else
traces=intersect(traces,minmax_traces);
end
end
if strcmp(varargin{cargin},'trange')
cargin=cargin+1;
eval(['tmin=',num2str(varargin{cargin}),';']);
cargin=cargin+1;
eval(['tmax=',num2str(varargin{cargin}),';']);
SegymatVerbose(['TRANGE : tmin=',num2str(tmin),' tmax=',num2str(tmax)])
end
% ENDIAN FORMAT
if strcmp(varargin{cargin},'endian')
cargin=cargin+1;
eval(['endian_tight=varargin{cargin};'])
if endian_tight=='l',
SegymatVerbose(['USING LITTLE ENDIAN TYPE'])
endian='ieee-le';
else
SegymatVerbose(['USING BIG ENDIAN TYPE'])
end
end
if strcmp(varargin{cargin},'revision')
cargin=cargin+1;
eval(['revision=',num2str(varargin{cargin}),';']);
SegymatVerbose(['USING REVISION : rev=',num2str(revision)])
end
if strcmp(varargin{cargin},'dsf')
cargin=cargin+1;
eval(['dsf=',num2str(varargin{cargin}),';']);
SegymatVerbose(['USING Data Sample Format : dsf=',num2str(dsf)])
end
if strcmp(varargin{cargin},'SkipData')
cargin=cargin+1;
eval(['SkipData=',num2str(varargin{cargin}),';']);
SegymatVerbose(['SKIPPNG DATA - READING ONLY HEADERS'])
end
if strcmp(varargin{cargin},'SegyHeader')
cargin=cargin+1;
SegyHeader=varargin{cargin};
SegymatVerbose(['USING LOADED SEGYHEADER'])
end
cargin=cargin+1;
end
if isempty(SkipData)==1,
SegymatVerbose([mfilename,' : Skip data is not set (defautls to 0)'],90)
SkipData=0; % [0] READ ONLY HEADER VALUES, [1] READ IN ALL DATA
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% OPEN FILE HANDLE
if exist('endian')==1,
SegymatVerbose([mfilename,' : ENDIAN : ',endian],1)
segyid = fopen(filename,'r',endian);
else
endian='ieee-be';
SegymatVerbose([mfilename,' : ENDIAN SET TO ',endian],0)
segyid = fopen(filename,'r','ieee-be'); % ALL DISK FILES ARE IN BIG
end % ENDIAN FORMAT, ACCORDING TO
% SEGY Y rev 1
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% BINARY HEADERS
if exist('SegyHeader')==0
SegyHeader=GetSegyHeader(segyid);
else
SegymatVerbose([mfilename,' - Using supplied SegyHeader'])
end
% APPLY CHANGES TO SEGY HEADER IF NEEDE
if isempty(revision)==0,
SegyHeader.SegyFormatRevisionNumber=revision;
SegymatVerbose([mfilename,' - Manually set SEG-Y revision to ',num2str(revision)])
end
if isempty(dsf)==0,
SegyHeader.DataSampleFormat=dsf;
end
% JUST SOME INFORMATION TO WRITE TO SCREEN :
Revision=SegyHeader.SegyFormatRevisionNumber;
if Revision>0, Revision=1; end
if (SegyHeader.DataSampleFormat>length(SegyHeader.Rev(Revision+1).DataSampleFormat));
SegymatVerbose([mfilename,' : WARNING : YOU HAVE SELECTED (OR THE FILE IS FORMATTED SUCH THAT) A DATASAMPLE FORMAT THAT IS NOT DEFINED. \nREMEBER IEEE IS NOT SPECIFIED IN THE SEGY REV0 STANDARD !'])
if (Revision==0)
SegymatVerbose([mfilename,' : TRYING TO USE REVISION 1 AS OPPOSED TO REVISION 0'])
Revision=1;
if (SegyHeader.DataSampleFormat>length(SegyHeader.Rev(Revision+1).DataSampleFormat));
SegymatVerbose([mfilename,' : FATAL ERROR : STILL THE DATASAMPLE FORMAT IS NOT SUPPRTED - EXITING (Report error to [email protected])'])
else
SegymatVerbose([mfilename,' : APPARENT SUCCES CHANING FROM Revision 0 to 1 - Continuing'])
SegyHeader.SegyFormatRevisionNumber=1; % FORCING REVISION TO BE 1 !!!
end
end
end
FormatName=SegyHeader.Rev(Revision+1).DataSampleFormat(SegyHeader.DataSampleFormat).name;
Format=SegyHeader.Rev(Revision+1).DataSampleFormat(SegyHeader.DataSampleFormat).format;
BPS=SegyHeader.Rev(Revision+1).DataSampleFormat(SegyHeader.DataSampleFormat).bps;
txt=['SegyRevision ',sprintf('%0.4g',Revision),', ',FormatName,'(',num2str(SegyHeader.DataSampleFormat),')'];
ns=SegyHeader.ns;
% YOU CAN FORCE FixedLengthTraceFlag=1;
% This will make the code much faster (especially when using
% the 'jump' option) but reading data with varying trace lengt will fail.
% It is here since many old data sets with Constant trace length
% has FixedLengthTraceFlag=0;
%
% As of version 1.01 this has been enable by default.
% Change the variable below to '0' if you do not want this behaviour
%
SegyHeader.FixedLengthTraceFlag=1;
SegymatVerbose([mfilename,' : Reading Data'],90);
% MAKE USE OF ReadSegyTrace to quickly read specific traces
%if ~isempty(traces)
% [Data,SegyTraceHeaders,SegyHeader]=ReadSegyTrace(filename,traces,SegyHeader);
% HeaderInfo=[];
% return;
%end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% READ DATA
%Segy=fread(segyid,4000,'float32');
fseek(segyid,0,'eof'); DataEnd=ftell(segyid);
fseek(segyid,0,'eof'); DataEnd=ftell(segyid);
DataStart=3600+3200*SegyHeader.NumberOfExtTextualHeaders;
fseek(segyid,DataStart,'bof'); % Go to the beginning of the file
fseek(segyid,DataStart,'bof'); % Go to the beginning of the file
ntraces=round((DataEnd-DataStart)./(240+(SegyHeader.ns)*(BPS/8)));
SegymatVerbose(['Number of Samples Per Trace=',num2str(SegyHeader.ns)])
SegymatVerbose(['Number of Traces=',num2str(ntraces)])
if (ntraces~=round(ntraces))
SegymatVerbose(['Trace lengths seems to vary. trying to read the file anyway'])
end
existJump=~isempty(jump);
existHeader=~isempty(header);
existTmin=~isempty(tmin);
existTmax=~isempty(tmax);
out_ntraces=ntraces;
if existJump==1, out_ntraces=ceil(ntraces/jump);end
if ~isempty(traces), out_ntraces=length(traces);end
dwaitbar=10;
if DataEnd./jump>1e+6, dwaitbar=10; end
if DataEnd./jump>1e+7, dwaitbar=50; end
if DataEnd./jump>1e+8, dwaitbar=200; end
traceinfile=0;
outtrace=0;
tic;
toc_old=toc;
if doWaitBar==1;
hw=waitbar(0,['Reading Segy - ',txt]);
end
% LOOP OVER TRACES
t0=now;
tlast=t0;
pos0=ftell(segyid);
while (~(ftell(segyid)>=DataEnd))
usetrace=1; % DEFAULT USING TRACE WHEN [1].
traceinfile=traceinfile+1;
if ~isempty(traces);
if (traceinfile>length(traces))
break
else
traceskip=240+(BPS/8)*SegyHeader.ns;
skip=DataStart+(traces(traceinfile)-1)*traceskip;
fseek(segyid,skip,'bof');
end
end
ishow=10000;
itime=1/(24*3600)*2; % Min time between verbose info to screen
if (((traceinfile/ishow)==round(traceinfile/ishow))&((now-tlast)>itime)),
tnow=now;
tlast=tnow;
posnow=ftell(segyid);
tend=t0+DataEnd.*(tnow-t0)./(posnow-pos0);
tleft=(tend-tnow)*3600*24;
txt=sprintf('Reading trace %d/%d, (%5.0fs left) (est end %s)',traceinfile,ntraces,tleft,datestr(tend));
toc_old=toc;
SegymatVerbose(txt)
end
TraceStart=ftell(segyid);
% IF 'JUMP' IS SET THEN CHECK IF THIS TRACE SHOULD BE SKIPPED
if existJump==1
if (traceinfile/jump)~=round(traceinfile/jump), usetrace=0; end
end
if ((usetrace==0)&(SegyHeader.FixedLengthTraceFlag==1)),
% SKIP FORWARD IN FILE'
skip=240+(BPS/8)*SegyHeader.ns;
fseek(segyid,skip,'cof');
SegymatVerbose([num2str(traceinfile),' - SKIPPING TRACE ... ',num2str(outtrace)],2)
elseif (SegyHeader.FixedLengthTraceFlag==0)
SegymatVerbose(sprintf('Using Fixed Length Trace as SegyHeader.FixedLengthTraceFlag=0',traceinfile),10);
SingleSegyTraceHeaders=GetSegyTraceHeader(segyid,TraceStart,Format,SegyHeader.ns,[]);
SingleSegyData.data=GetSegyTraceData(segyid,SingleSegyTraceHeaders.ns,SegyHeader);
else
SingleSegyTraceHeaders=GetSegyTraceHeader(segyid,TraceStart,Format,SegyHeader.ns,[]);
SingleSegyData.data=GetSegyTraceData(segyid,SegyHeader.ns,SegyHeader);
if SingleSegyTraceHeaders.TraceNumber<1
SingleSegyTraceHeaders.TraceNumber=traceinfile;
SegymatVerbose(sprintf('TraceNumber malformatetd. Setting TraceNumber=%d',traceinfile),10);
end
SegymatVerbose(sprintf('ns=%d, Trace in line : %d, Trace in file : %d, ns=%10.5f dt=%10.5f',SingleSegyTraceHeaders.ns,SingleSegyTraceHeaders.TraceSequenceLine,SingleSegyTraceHeaders.TraceSequenceFile,SingleSegyTraceHeaders.ns,SingleSegyTraceHeaders.dt),10)
end
% IF HEADER MIN MAX HAS BEEN CHOSEN, THEN CHECK THAT TRACE IS GOOD ENOUGH
if ((existHeader==1)&(usetrace==1))
headervalue=getfield(SingleSegyTraceHeaders,header);
if ((headervalue<headermin)|(headervalue>headermax))
usetrace=0;
end
end
% USE THIS TRACE IF usetrace=1 !!
if usetrace==1,
%% IF TIME RANGE IS SPECIFIED, THEN EXTRACT THIS
if (existTmin==1)&(existTmax==1)
% NEXT LINE SHOULD CONSIDER THAT ns in Trace and Segy Header
% could vary !!!
origtrange=[1:1:SegyHeader.ns].*SegyHeader.dt.*1e-6+SingleSegyTraceHeaders.DelayRecordingTime.*1e-3;
gooddata=find(origtrange>tmin & origtrange<tmax);
SingleSegyData.data=SingleSegyData.data(gooddata);
% CHECK NEXT LINE TAHT DelatRec... is in micro seconds
SingleSegyTraceHeaders.DelayRecordingTime=tmin.*1e+3;
SingleSegyTraceHeaders.ns=length(gooddata);
ns=length(gooddata); % for use below
end
outtrace=outtrace+1;
if (outtrace==1),
% Preallocate RAM
ta1=now;
SegymatVerbose(sprintf('Pre allocating RAM ntraces=%d out_traces=%d',ntraces,out_ntraces));
SegyData=repmat(struct('data',zeros(ns,1)),1,out_ntraces);
SegyTraceHeaders=repmat(SingleSegyTraceHeaders,1,out_ntraces);
%whos SegyData SegyTraceHeaders
%save T1
ta2=now;
t0=t0+ta2-ta1;
end
SegyData(outtrace).data=SingleSegyData.data;
SegyTraceHeaders(outtrace)=SingleSegyTraceHeaders;
if doWaitBar==1,
if ((outtrace/dwaitbar)==round(outtrace/dwaitbar))
waitbar(ftell(segyid)/DataEnd,hw);
end
end
end
end
%save T2
%whos SegyData SegyTraceHeaders
if outtrace==0
SegymatVerbose(sprintf('%s : No traces read!',mfilename));
SegyTraceHeaders=[];
Data=[];
return
end
if doWaitBar==1
try
close(hw);
end
end
SegymatVerbose([mfilename,' : Elapsed time ',num2str(toc),' ended at ',datestr(now)]);
t=outtrace;
% Write time to SegyHeader
SegyHeader.ns=ns;
SegyHeader.time=[1:1:SegyHeader.ns].*SegyHeader.dt./1e+6+SegyTraceHeaders(1).DelayRecordingTime./1e+3;
% Make sure that only read SegyTraceHEaders are returned
if outtrace~=out_ntraces
SegyTraceHeaders=SegyTraceHeaders(1:outtrace);
end
% MOVE DATA from SegyData.data to a regular variable
% THIS STEP COULD BE AVOIDED WHEN FixedTraceLength=1, which is almost
% allways the case... Should speed up things and reduce memory reqs.
if SkipData==1,
Data=[];
else
try
Data=[SegyData(1:outtrace).data];
catch
Data=zeros(ns,outtrace);
for i=1:outtrace
try
Data(:,i)=SegyData(i).data;
catch
errmsg=lasterr;
if isempty(SegyData(i).data)
errmsg='Empty data in trace';
elseif (strfind(errmsg, 'In an assignment A(:,matrix) = B, the number of rows in A and B'))
nns=length(SegyData(i).data);
if nns<ns
errmsg='Length of trace varies - padding with zeros';
Data(1:nns,i)=SegyData(i).data;
else
errmsg='Length of trace varies - truncating';
Data(:,i)=SegyData(i).data(1:ns);
end
end
SegymatVerbose(sprintf('Had a problem at trace %d : %s',i,errmsg))
end
end
end
end
|
github
|
Abakumov/MLIB-master
|
MergeSegy.m
|
.m
|
MLIB-master/OTHER/SegyMAT/MergeSegy.m
| 1,261 |
utf_8
|
6b32ecfc683f3af7b63ec0340bccfb0f
|
% MergeSegy : Merge multiple SEGY files
%
% Example :
% MergeSegy('*.sgy','merge.sgy')
%
% f{1}='file1.sgy';
% f{2}='file2.sgy';
% f{3}='file3.sgy';
% MergeSegy(f,'merge.sgy')
%
%
% Note: All imput segy files must have the same constant trace length
% The SEGY header of the merged SEGY file will be the SEGY header
% form the first input SEGY file.
%
%
function [file_out,D,STH,SegyHeader]=MergeSegy(files,file_out)
if nargin<2
file_out='segymerge.sgy';
end
if isstr(files)
file_names=dir(files);
end
if iscell(files);
for i=1:length(files);
file_names(i).name=files{i};
end
end
for i=1:length(file_names);
[Data,SegyTraceHeaders,SegyHeader]=ReadSegy(file_names(i).name);
if i==1;
ss=size(Data);
else
%check size
if (length(find(ss==size(Data)))~=2)
SegymatVerbose(sprintf('%s : Data sizes differs',mfilename),-1);
end
end
if i==1;
D=Data;
STH=SegyTraceHeaders;
else
n_sth=length(STH);
for j=1:length(SegyTraceHeaders)
STH(j+n_sth)=SegyTraceHeaders(j);
STH(j+n_sth).TraceNumber=j;
end
D=[D Data];
end
end
WriteSegyStructure(file_out,SegyHeader,STH,D);
|
github
|
Abakumov/MLIB-master
|
WriteSegyStructure.m
|
.m
|
MLIB-master/OTHER/SegyMAT/WriteSegyStructure.m
| 3,137 |
utf_8
|
4df12fa8cbb0f2891b7fd5c2561cc280
|
% WriteSegyStructure : writes data to disk using SEGY REV 0 and 1 standards.
%
% EX
% WriteSegyStructure('datacube.segy',SegyHeader,SegyTraceHeaders,Data);
%
% To force the use of SEG Y revision 0
% WriteSegyStructure('datacube.segy',SegyHeader,SegyTraceHeaders,Data,'revision',0);
% To force the use of SEG Y revision 1
% WriteSegyStructure('datacube.segy',SegyHeader,SegyTraceHeaders,Data,'revision',1);
% To force the data sampling format to be IBM Floating Point
% WriteSegyStructure('datacube.segy',SegyHeader,SegyTraceHeaders,Data,'dsf',1);
%
% To force the use of SEG Y revision 0 and data sampling format IEEE :
% WriteSegyStructure('datacube.segy',SegyHeader,SegyTraceHeaders,Data,'revision',1,'dsf',5);
%
% See the dokumentation for for proper values of 'dsf'
%
%
%
% (C) 2001-2004, Thomas Mejer Hansen, [email protected]/[email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
%
%
function SegyHeader=WriteSegyStructure(filename,SegyHeader,SegyTraceHeaders,Data,varargin)
for i=1:2:length(varargin)
var=varargin{i};
val=varargin{i+1};
eval([var,'=[',num2str(val),'];']);
end
if exist('revision')==1,
if revision==0,
SegyHeader.SegyFormatRevisionNumber=0;
else
SegyHeader.SegyFormatRevisionNumber=100;
end
SegymatVerbose([mfilename,' : Using SEG Y revision ',num2str(revision)])
end
if exist('dsf'),
SegyHeader.DataSampleFormat=dsf;
SegymatVerbose([mfilename,' : Using Data Sample Format ',num2str(dsf)])
end
segyid = fopen(filename,'w','b'); % ALL DISK FILES ARE IN BIG
% ENDIAN FORMAT, ACCORDING SEG
% Y rev 1
% JUST SOME INFORMATION TO WRITE TO SCREEN :
Revision=SegyHeader.SegyFormatRevisionNumber;
if Revision>0, Revision=1; end
%Format=SegyHeader.Rev(Revision+1).DataSampleFormat(SegyHeader.DataSampleFormat).name;
%txt=['SegyRevision ',sprintf('%0.4g',Revision),', ',Format,'(',num2str(SegyHeader.DataSampleFormat),')'];
txt='';
SegyHeader=PutSegyHeader(segyid,SegyHeader);
ntraces=size(Data,2);
hw=waitbar(0,['Writing to SEGY-file : ',filename,' - ',txt]);
for i=1:ntraces;
if (i/100)==round(i/100),
SegymatVerbose(['writing trace ',num2str(i),' of ',num2str(ntraces),', filepos=',num2str(ftell(segyid))])
waitbar(i/ntraces,hw)
end
PutSegyTrace(segyid,Data(:,i),SegyTraceHeaders(i),SegyHeader);
end
close(hw)
fclose(segyid);
|
github
|
Abakumov/MLIB-master
|
PutSegyHeader.m
|
.m
|
MLIB-master/OTHER/SegyMAT/PutSegyHeader.m
| 9,215 |
utf_8
|
8f388ebf1ecaf07cf9c4fb98057dc2b7
|
% PutSegyHeader : Writes SEG-Y header to disk.
% PutSegyHeader(segyid,SegyHeader)
%
% (C) 2001-2004, Thomas Mejer Hansen, [email protected]/[email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
%
function SegyHeader=PutSegyHeader(segyid,SegyHeader);
NA=0;
if isfield(SegyHeader,'Rev')==0
SegyHeader.Rev=GetSegyHeaderBasics;
end
if (isfield(SegyHeader,'DataSampleFormat')==0)&(isfield(SegyHeader,'SegyFormatRevisionNumber')==0)
SegyHeader.DataSampleFormat=5; % '5'->4-byte IEEE floating point
SegyHeader.SegyFormatRevisionNumber=100;
SegymatVerbose([mfilename,' : Using datasample format : ',SegyHeader.Rev(2).DataSampleFormat(SegyHeader.DataSampleFormat).name],1)
SegymatVerbose([mfilename,' : Using SEG Y revision : ',num2str(floor(SegyHeader.SegyFormatRevisionNumber/100))],1)
end
% SET Revsion number. Always use revision 1, if not otherwise specified.
if (isfield(SegyHeader,'SegyFormatRevisionNumber')==0)
SegyHeader.SegyFormatRevisionNumber=100;
SegymatVerbose([mfilename,' : Using SEG Y revision : ',num2str(floor(SegyHeader.SegyFormatRevisionNumber/100))],1)
end
% SET DATA SAMPLE FORMAT IF NOT SPECIFIED
% Rev0->IBM FLOATING POINT
% Rev1->IEEE FLOATING POINT
if (isfield(SegyHeader,'DataSampleFormat')==0)
if SegyHeader.SegyFormatRevisionNumber==0
SegyHeader.DataSampleFormat=1; % '1'->IBM floating point
SegymatVerbose([mfilename,' : Using datasample format : ',SegyHeader.Rev(1).DataSampleFormat(SegyHeader.DataSampleFormat).name],1)
else
SegyHeader.DataSampleFormat=5; % '5'->4-byte IEEE floating point
SegymatVerbose([mfilename,' : Using datasample format : ',SegyHeader.Rev(2).DataSampleFormat(SegyHeader.DataSampleFormat).name],1)
end
end
if isfield(SegyHeader,'TextualFileHeader')
% MAKE SURE LENGTH IF Text.. is 3200
if length(SegyHeader.TextualFileHeader)<3200
dummyTXT=SegyHeader.TextualFileHeader;
SegyHeader.TextualFileHeader=zeros(3200,0);
SegyHeader.TextualFileHeader(1:length(dummyTXT))=dummyTXT;
end
else
SegyHeader.TextualFileHeader=sprintf('%3200s','SEGY READER ([email protected])');
end
if ~isfield(SegyHeader,'Job'), SegyHeader.Job=NA; end
if ~isfield(SegyHeader,'Line'), SegyHeader.Line=NA; end
if ~isfield(SegyHeader,'Reel'), SegyHeader.Reel=NA; end
if ~isfield(SegyHeader,'DataTracePerEnsemble'), SegyHeader.DataTracePerEnsemble=NA;end
if ~isfield(SegyHeader,'AuxiliaryTracePerEnsemble'), SegyHeader.AuxiliaryTracePerEnsemble=0;end
if ~isfield(SegyHeader,'dt'), SegyHeader.dt=4000; end
if ~isfield(SegyHeader,'dtOrig'), SegyHeader.dtOrig=NA; end
if ~isfield(SegyHeader,'ns'), SegyHeader.ns=NA; end
if ~isfield(SegyHeader,'nsOrig'), SegyHeader.nsOrig=NA; end
if ~isfield(SegyHeader,'DataSampleFormat'), SegyHeader.DataSampleFormat=5; end % '5'->4-byte IEEE floating point
if ~isfield(SegyHeader,'EnsembleFold'), SegyHeader.EnsembleFold=NA; end
if ~isfield(SegyHeader,'TraceSorting'), SegyHeader.TraceSorting=NA; end
if ~isfield(SegyHeader,'VerticalSumCode'), SegyHeader.VerticalSumCode=NA; end
if ~isfield(SegyHeader,'SweepFrequencyStart');SegyHeader.SweepFrequencyStart=NA; end
if ~isfield(SegyHeader,'SweepFrequencyEnd');SegyHeader.SweepFrequencyEnd=NA; end
if ~isfield(SegyHeader,'SweepLength');SegyHeader.SweepLength=NA; end
if ~isfield(SegyHeader,'SweepType');SegyHeader.SweepType=NA; end
if ~isfield(SegyHeader,'SweepChannel');SegyHeader.SweepChannel=NA; end
if ~isfield(SegyHeader,'SweepTaperlengthStart');SegyHeader.SweepTaperlengthStart=NA; end
if ~isfield(SegyHeader,'SweepTaperLengthEnd');SegyHeader.SweepTaperLengthEnd=NA; end
if ~isfield(SegyHeader,'TaperType');SegyHeader.TaperType=NA; end
if ~isfield(SegyHeader,'CorrelatedDataTraces');SegyHeader.CorrelatedDataTraces=NA; end
if ~isfield(SegyHeader,'BinaryGain');SegyHeader.BinaryGain=NA; end
if ~isfield(SegyHeader,'AmplitudeRecoveryMethod');SegyHeader.AmplitudeRecoveryMethod=NA; end
if ~isfield(SegyHeader,'MeasurementSystem');SegyHeader.MeasurementSystem=1; end %1-Meters, 2-Feet
if ~isfield(SegyHeader,'ImpulseSignalPolarity');SegyHeader.ImpulseSignalPolarity=NA; end
if ~isfield(SegyHeader,'VibratoryPolarityCode');SegyHeader.VibratoryPolarityCode=NA; end
% 3261-3500 UNASSIGNED
if ~isfield(SegyHeader,'Unassigned1');SegyHeader.Unassigned1=NA*ones(1,120); end
%if ~isfield(SegyHeader,'SegyFormatRevisionNumber'); SegyHeader.SegyFormatRevisionNumber=100; end % ACCORDING TO SEGY REV1 draft 6
if ~isfield(SegyHeader,'FixedLengthTraceFlag');SegyHeader.FixedLengthTraceFlag=1; end % ALL TRACES HAVE THE SAME dt AND ns
if ~isfield(SegyHeader,'NumberOfExtTextualHeaders'); SegyHeader.NumberOfExtTextualHeaders=0; end % WE DO NOT YET USE TEXTURAL HEADERS as can be done according to draft 6
% 3506-3600 UNASSIGNED
if ~isfield(SegyHeader,'Unassigned2');SegyHeader.Unassigned2=NA*ones(1,47); end
% IF EXTENDED TEXTUAL FILE HEADERS EXISTS THEN WRITE THEM TO DISK
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% WRITE TO DISK
%
fseek(segyid,0,'bof');
fwrite(segyid,SegyHeader.TextualFileHeader(1:3200),'uchar'); % 1-3200
fwrite(segyid,SegyHeader.Job,'int32'); % 3204
fwrite(segyid,SegyHeader.Line,'int32'); % 3208
fwrite(segyid,SegyHeader.Reel,'int32'); % 3212
fwrite(segyid,SegyHeader.DataTracePerEnsemble,'int16'); % 3214
fwrite(segyid,SegyHeader.AuxiliaryTracePerEnsemble,'int16'); % 3216
fwrite(segyid,SegyHeader.dt,'uint16'); % 3218
fwrite(segyid,SegyHeader.dtOrig,'uint16'); % 3220
fwrite(segyid,SegyHeader.ns,'uint16'); % 3222
fwrite(segyid,SegyHeader.nsOrig,'uint16'); % 3224
fwrite(segyid,SegyHeader.DataSampleFormat,'int16'); % 3226
fwrite(segyid,SegyHeader.EnsembleFold,'int16');
fwrite(segyid,SegyHeader.TraceSorting,'int16'); % 3228
fwrite(segyid,SegyHeader.VerticalSumCode,'int16'); % 3230
fwrite(segyid,SegyHeader.SweepFrequencyStart,'int16'); % 3232
fwrite(segyid,SegyHeader.SweepFrequencyEnd,'int16'); % 3234
fwrite(segyid,SegyHeader.SweepLength,'int16'); % 3236
fwrite(segyid,SegyHeader.SweepType,'int16'); % 3238
fwrite(segyid,SegyHeader.SweepChannel,'int16'); % 3240
fwrite(segyid,SegyHeader.SweepTaperlengthStart,'int16'); % 3242
fwrite(segyid,SegyHeader.SweepTaperLengthEnd,'int16'); % 3244
fwrite(segyid,SegyHeader.TaperType,'int16'); % 3246
fwrite(segyid,SegyHeader.CorrelatedDataTraces,'int16'); % 3248
fwrite(segyid,SegyHeader.BinaryGain,'int16'); % 3250
fwrite(segyid,SegyHeader.AmplitudeRecoveryMethod,'int16'); % 3252
fwrite(segyid,SegyHeader.MeasurementSystem,'int16'); % 3254
fwrite(segyid,SegyHeader.ImpulseSignalPolarity,'int16'); % 3256
fwrite(segyid,SegyHeader.VibratoryPolarityCode,'int16'); % 3258
% 3261-3500 UNASSIGNED1 => (120 int32 = 240 bytes)
fwrite(segyid,SegyHeader.Unassigned1,'int16'); % 3260
%SegymatVerbose(ftell(segyid),10);
%fseek(segyid,3500,'bof');
fwrite(segyid,SegyHeader.SegyFormatRevisionNumber,'uint16'); % 3500
fwrite(segyid,SegyHeader.FixedLengthTraceFlag,'int16'); % 3502
fwrite(segyid,SegyHeader.NumberOfExtTextualHeaders,'uint16'); % 3504
% 3506-3600 UNASSIGNED2 => 94/2=47 int16
fwrite(segyid,SegyHeader.Unassigned2,'int16'); % 3506
%
%
%
if SegyHeader.NumberOfExtTextualHeaders>0
n=SegyHeader.NumberOfExtTextualHeaders;
SegymatVerbose(sprintf('Writing %d Extended Textual File Headers',n));
if isfield(SegyHeader,'ExtTextualHeader')
% MAKE SURE LENGTH IF Text.. is 3200*n
if length(SegyHeader.ExtTextualHeader)<(3200*n)
dummyTXT=SegyHeader.ExtTextualHeader;
SegyHeader.ExtTextualHeader=zeros(n*3200,0);
SegyHeader.ExtTextualHeader(1:length(dummyTXT))=dummyTXT;
end
else
SegyHeader.ExtTextualHeader=sprintf('%3200s','SEGY READER ([email protected])');
for i=2:n,
SegyHeader.ExtTextualHeader=[SegyHeader.ExtTextualHeader,sprintf('%3200s','SEGY READER ([email protected])')];
end
end
% WRITE TEXTUAL FILE HEADER
fwrite(segyid,SegyHeader.ExtTextualHeader(1:(n*3200)),'uchar'); % 1:(n*3200)
end
Revision=SegyHeader.SegyFormatRevisionNumber;
if Revision>0, Revision=1; end
Format=SegyHeader.Rev(Revision+1).DataSampleFormat(SegyHeader.DataSampleFormat).name;
SegymatVerbose([mfilename,' - SegyRevision ',sprintf('%0.4g',Revision),', ',Format],2)
|
github
|
Abakumov/MLIB-master
|
SegyMAT_GAIN.m
|
.m
|
MLIB-master/OTHER/SegyMAT/SegyMAT_GAIN.m
| 2,629 |
utf_8
|
3c9eb45cfb08e9989024aee07fc78052
|
% SegyMAT_GAIN : Gain plugin for SegyMAT
%
% [Data,SegyTraceHeaders,SegyHeader]=SegyMAT_GAIN(Data,SegyTraceHeaders,SegyHeader,varargin);
%
% ex. AGC using AGC window of 100 ms :
% [Data]=SegyMAT_GAIN(Data,SegyTraceHeaders,SegyHeader,'agc',.1);
% ex. apply t^(pow), pow=2
% [Data]=SegyMAT_GAIN(Data,SegyTraceHeaders,SegyHeader,'pow',2);
%
%
% (C) Thomas Mejer Hansen ([email protected]), 2002
%
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
%
function [Data,SegyTraceHeaders,SegyHeader]=SegyMAT_GAIN(Data,SegyTraceHeaders,SegyHeader,varargin);
nv=0;
for i=1:length(varargin)
if strcmp(varargin{i},'agc')
type=1;
window=varargin{i+1};
end
if strcmp(varargin{i},'pow')
type=2;
pow=varargin{i+1};
end
end
if type==1
disp([mfilename,' AGC'])
for it=1:size(Data,2)
disp([mfilename,' AGC trace : ',num2str(it)])
% Trace Data
TraceData=Data(:,it);
% Window Length
nsw=round(window./(SegyTraceHeaders(it).dt./1e+6));
nshalf=floor(nsw/2);
startsample=ceil(nsw/2);
endsample=length(TraceData)-floor(nsw);
for is=startsample:1:endsample;
range=[is-nshalf+1:1:is+nshalf];
gain=mean(abs(TraceData(range)));
if gain~=0
TraceData(is)=TraceData(is)./mean(abs(TraceData(range)));
% APPLY TO TOP
if is==startsample
for i=[1:startsample-1];
TraceData(i)=TraceData(i)./mean(abs(TraceData(range)));
end
end
if is==endsample
for i=[endsample+1:1:length(TraceData)];
TraceData(i)=TraceData(i)./gain;
end
end
end
end
Data(:,it)=TraceData;
end % END LOOP OVER TRACES
end % END TYPE
if type==2
disp([mfilename,' POW'])
for it=1:size(Data,2)
% disp([mfilename,' POW trace : ',num2str(it)])
t=[1:1:SegyTraceHeaders(it).ns]*SegyTraceHeaders(it).dt./1e+6+SegyTraceHeaders(it).DelayRecordingTime./1e+3;
tp=t.^(pow)';
Data(:,it)=Data(:,it).*tp;
end
end
|
github
|
Abakumov/MLIB-master
|
WriteSegy.m
|
.m
|
MLIB-master/OTHER/SegyMAT/WriteSegy.m
| 6,194 |
utf_8
|
228dcbbe6b1f9db73888e310daa150ea
|
% WriteSegy : writes data to disk using SEGY REV 1 standard.
%
% EX
% WriteSegy('datacube.segy',data,'dt',.004,'Inline3D',Inline,'Crossline3D',Crossline,'cdpX',X,'cdpY',Y);
%
% to use a specific SEG revision use :
% WriteSegy('test.segy',seisdata,'revision',0); % SEG-Y Revision 0
% WriteSegy('test.segy',seisdata,'revision',1); % SEG-Y Revision 1
%
% to use a specific Data Sampling Format use :
% WriteSegy('test.segy',seisdata,'dsf',1); % IBM FLAOTING POINT
%
% Forice Revision 1 and IEEE Floating point :
% WriteSegy('test.segy',seisdata,'dsf',5,'revision',1);
%
% See also : WriteSegyStructure, WriteSu, WriteSuStructure
%
%
% (C) 2001-2007, Thomas Mejer Hansen, [email protected]/[email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
%
function WriteSegy(filename,data,varargin);
[ns,ntraces]=size(data);
for i=1:2:length(varargin)
var=varargin{i};
val=varargin{i+1};
eval([var,'=[',num2str(val),'];']);
end
if exist('dt')~=1
dt=0.004;
SegymatVerbose([mfilename,' - No dt set. Using dt=',num2str(dt)],0)
end
%%%%%%%%%%
% SET UP SegyHeader structure.
if exist('TextualFileHeader'), SegyHeader.TextualFileHeader=TextualFileHeader; end
if exist('Job')==1, SegyHeader.Job=Job; end;
if exist('Line')==1, SegyHeader.Line=Line; end
if exist('Reel')==1, SegyHeader.Reel=Reel; end
if exist('DataTracePerEnsemble')==1, SegyHeader.DataTracePerEnsemble=DataTracePerEnsemble; end
if exist('AuxiliaryTracePerEnsemble')==1, SegyHeader.AuxiliaryTracePerEnsemble=AuxiliaryTracePerEnsemble; end
if exist('dt')==1, SegyHeader.dt=dt.*1e+6; end
if exist('dtOrig')==1, SegyHeader.dtOrig=dtOrig; end
if exist('ns')==1, SegyHeader.ns=ns; end
if exist('nsOrig')==1, SegyHeader.nsOrig=nsOrig; end
if exist('EnsembleFold')==1, SegyHeader.EnsembleFold=EnsembleFold; end
if exist('TraceSorting')==1, SegyHeader.TraceSorting=TraceSorting; end
if exist('VerticalSumCode')==1, SegyHeader.VerticalSumCode=VerticalSumCode; end
%%%%%%%%%%
%% CHOOSE WHICH SEGY REVISION AND DATATYPE TO USE
%% DEFAULT IS REVISION 1, 4-byte IEEE
% IF A SPECFIC REVISION HAS BEEN CHOSEN, USE THAT
if exist('revision')==1,
if revision==1,
SegyHeader.SegyFormatRevisionNumber=100;
else
SegyHeader.SegyFormatRevisionNumber=0;
end
SegymatVerbose([mfilename,' : Using user specified SEG Y revision : ',num2str(revision)],1)
end
% IF A SPECFIC DATA SAMPLING FORMAT HAS BEEN SELECTED USE THAT
if exist('dsf')==1,
SegyHeader.DataSampleFormat=dsf;
SegymatVerbose([mfilename,' : Using user specified Data Sample Format : ',num2str(revision)],1)
end
% UNCOMMENT THE FOLLOWING TWO LINES TO USE REVISION 1 (2002)
%SegyHeader.SegyFormatRevisionNumber=100; % 2002 SEG Y STYLE
%SegyHeader.DataSampleFormat=2; % '1'->4-byte IBM floating point
% '2'->4-byte two's complement integer
% '3'->2-byte two's complement integer
% '5'->4-byte IEEE floating point (default)
% '8'->1-byte two's complement integer
% UNCOMMENT THE FOLLOWING TWO LINES TO USE REVISION 0 (1975)
%SegyHeader.SegyFormatRevisionNumber=0; % 1975 SEoG Y STYLE
%SegyHeader.DataSampleFormat=1; % '1'->4-byte IBM Floating Point
% OPEN SEGY FILE HANDLE
segyid = fopen(filename,'w','b'); % ALL DISK FILES ARE IN BIG
% ENDIAN FORMAT, ACCORDING SEG
% Y rev 1
% Write SEGY HEADER
SegyHeader=PutSegyHeader(segyid,SegyHeader);
for i=1:ntraces;
if (i/100)==round(i/100),
SegymatVerbose(['writing trace ',num2str(i),' of ',num2str(ntraces)],0);
end
% Basic TraceHeader information
% INITALIZE SEGY TRACE HEADER
if exist('SegyTraceHeader')==0;
SegyTraceHeader=InitSegyTraceHeader(ns,dt*1e+6);
end
if exist('TraceNumber')==0
SegyTraceHeader.TraceNumber=i;
SegyTraceHeader.TraceSequenceFile=i;
end
% Update TraceHeader information if available
if exist('cdpX')==1,SegyTraceHeader.cdpX = cdpX(i);end
if exist('offset')==1,SegyTraceHeader.offset = offset(i);end
if exist('cdpY')==1,SegyTraceHeader.cdpY = cdpY(i);end
if exist('Inline3D')==1,SegyTraceHeader.Inline3D = Inline3D(i);end
if exist('Crossline3D')==1,SegyTraceHeader.Crossline3D=Crossline3D(i);end
if exist('YearDataRecorded')==1,SegyTraceHeader.YearDataRecorded=YearDataRecorded(i);end
if exist('DayOfYear')==1,SegyTraceHeader.DayOfYear=DayOfYear(i);end
if exist('HourOfDay')==1,SegyTraceHeader.HourOfDay=HourOfDay(i);end
if exist('MinuteOfOur')==1,SegyTraceHeader.MinuteOfOur=MinuteOfOur(i);end
if exist('SecondOfMinute')==1,SegyTraceHeader.SecondOfMinute=SecondOfMinute(i);end
if exist('TimeBaseCode')==1,SegyTraceHeader.TimeBaseCode=TimeBaseCode(i);end
% Write the Trace
PutSegyTrace(segyid,data(:,i),SegyTraceHeader,SegyHeader);
end
% CLOSE SEGY FILE HANDLE
fclose(segyid);
|
github
|
Abakumov/MLIB-master
|
SegymatRevision.m
|
.m
|
MLIB-master/OTHER/SegyMAT/SegymatRevision.m
| 1,329 |
utf_8
|
23a4b2bcd7aa58b83f3ccc8dde4a5a46
|
% SegymatRevision - Returns the revision history
%
% Call : [Revision]=SegymatRevision
%
%
% (C) 2001-2011, Thomas Mejer Hansen, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
%
function [Rev]=SegymatRevision;
revisionfile=[fileparts(which('ReadSegy')),'/REVISION'];
fid=fopen(revisionfile,'r');
cl=0;
while 1
cl=cl+1;
currentline=fgetl(fid);
if ~ischar(currentline), break, end
st{cl} = currentline;
end
fclose(fid);
if nargout==0,
SegymatVerbose(['SegyMAT Revision History'])
for i=1:length(st);
SegymatVerbose(st{i})
end
else
Rev=st;
end
|
github
|
Abakumov/MLIB-master
|
isoctave.m
|
.m
|
MLIB-master/OTHER/SegyMAT/isoctave.m
| 117 |
utf_8
|
0a3b59cac8a9b483e95a3085be4387ab
|
% isoctave : checks of octave
function r=isoctave
v=version;
if (str2num(v(1)))>4
r=0;
else
r=1;
end
|
github
|
Abakumov/MLIB-master
|
ascii2ebcdic.m
|
.m
|
MLIB-master/OTHER/SegyMAT/ascii2ebcdic.m
| 3,940 |
utf_8
|
80500db27103dcf156237c55d951a2fa
|
% ascii2ebcdic : Converts ASCII formatted text to EBCDIC formatted text
%
% CALL : ebcdic=ascii2ebcdic(ascii);
%
% ascii : Array on unsigned integers
% ebcdic : Array on unsigned integers
%
% (C) 2002-2009, Thomas Mejer Hansen, [email protected]/[email protected]
%
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
%
function ebcdic=ascii2ebcdic(ascii)
ebcdic_arr=[
'00';'01';'02';'03';'04';'05';'06';'07';'08';'09';
'0A';'0B';'0C';'0D';'0E';'0F';'10';'11';'12';'13';
'14';'15';'16';'17';'18';'19';'1A';'1B';'1C';'1D';
'1E';'1F';'20';'21';'22';'23';'24';'25';'26';'27';
'28';'29';'2A';'2B';'2C';'2D';'2E';'2F';'30';'31';
'32';'33';'34';'35';'36';'37';'38';'39';'3A';'3B';
'3C';'3D';'3E';'3F';'40';'4A';'4B';'4C';'4D';'4E';
'4F';'50';'5A';'5B';'5C';'5D';'5E';'5F';'60';'61';
'6A';'6B';'6C';'6D';'6E';'6F';'79';'7A';'7B';'7C';
'7D';'7E';'7F';'81';'82';'83';'84';'85';'86';'87';
'88';'89';'91';'92';'93';'94';'95';'96';'97';'98';
'99';'A1';'A2';'A3';'A4';'A5';'A6';'A7';'A8';'A9';
'C0';'C1';'C2';'C3';'C4';'C5';'C6';'C7';'C8';'C9';
'D0';'D1';'D2';'D3';'D4';'D5';'D6';'D7';'D8';'D9';
'E0';'E2';'E3';'E4';'E5';'E6';'E7';'E8';'E9';'F0';
'F1';'F2';'F3';'F4';'F5';'F6';'F7';'F8';'F9';'FF';
'00';'01';'02';'03';'37';'2D';'2E';'2F';'2F';'16';
'05';'25';'0B';'0C';'0D';'10';'11';'12';'13';'3C';
'3D';'32';'26';'18';'3F';'27';'1C';'1D';'1D';'1E';
'1F';'07';'40';'5A';'7F';'7B';'5B';'6C';'50';'7D';
'4D';'5D';'5C';'4E';'6B';'60';'4B';'61';'F0';'F1';
'F2';'F3';'F4';'F5';'F6';'F7';'F8';'F9';'7A';'5E';
'4C';'7E';'6E';'6F';'7C';'00';'E0';'00';'00';'6D';
'79';'C0';'4F';'D0';'A1'];
ascii_arr=[
'00';'01';'02';'03';'9C';'09';'86';'7F';'97';'8D';
'8E';'0B';'0C';'0D';'0E';'0F';'10';'11';'12';'13';
'9D';'85';'08';'87';'18';'19';'92';'8F';'1C';'1D';
'1E';'1F';'80';'81';'82';'83';'84';'0A';'17';'1B';
'88';'89';'8A';'8B';'8C';'05';'06';'07';'90';'91';
'16';'93';'94';'95';'96';'04';'98';'99';'9A';'9B';
'14';'15';'9E';'1A';'20';'A2';'2E';'3C';'28';'2B';
'7C';'26';'21';'24';'2A';'29';'3B';'AC';'2D';'2F';
'A6';'2C';'25';'5F';'3E';'3F';'60';'3A';'23';'40';
'27';'3D';'22';'61';'62';'63';'64';'65';'66';'67';
'68';'69';'6A';'6B';'6C';'6D';'6E';'6F';'70';'71';
'72';'7E';'73';'74';'75';'76';'77';'78';'79';'7A';
'7B';'41';'42';'43';'44';'45';'46';'47';'48';'49';
'7D';'4A';'4B';'4C';'4D';'4E';'4F';'50';'51';'52';
'5C';'53';'54';'55';'56';'57';'58';'59';'5A';'30';
'31';'32';'33';'34';'35';'36';'37';'38';'39';'9F';
'00';'01';'02';'03';'04';'05';'06';'07';'07';'08';
'09';'0A';'0B';'0C';'0D';'10';'11';'12';'13';'14';
'15';'16';'17';'18';'1A';'1B';'1C';'1D';'1D';'1E';
'1F';'7F';'20';'21';'22';'23';'24';'25';'26';'27';
'28';'29';'2A';'2B';'2C';'2D';'2E';'2F';'30';'31';
'32';'33';'34';'35';'36';'37';'38';'39';'3A';'3B';
'3C';'3D';'3E';'3F';'40';'5B';'5C';'5D';'5E';'5F';
'60';'7B';'7C';'7D';'7E'
];
ascii_dec_array=hex2dec(ascii_arr);
ebcdic_dec_array=hex2dec(ebcdic_arr);
for i=1:length(ascii)
m=find(ascii_dec_array==ascii(i));
if length(m)>1,
m=m(1);
end
if length(m)==0,
ebcdic(i)=0;
else
ebcdic(i)=(ebcdic_dec_array(m));
end
end
|
github
|
Abakumov/MLIB-master
|
ReadSegyHeader.m
|
.m
|
MLIB-master/OTHER/SegyMAT/ReadSegyHeader.m
| 5,838 |
utf_8
|
8cf659b69eb0324bdf8f633c00465167
|
% ReadSegyHeader : Reads a SEG Y Binary Header
%
% Call :
% [SegyHeader]=ReadSegyHeader(filename);
%
% To read using little endian :
% [SegyHeader]=ReadSegyHeader(filename,'endian','l');
%
% (C) 2001-2004, Thomas Mejer Hansen, [email protected]/[email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
%
%
function [SegyHeader]=ReadSegyHeader(filename,varargin);
if ~(exist(filename)==2'),
SegymatVerbose([mfilename,' : ', filename,' does not exist !'])
Data=[];SegyTraceHeaders=[];SegyHeader=[];HeaderInfo=[];
return
end
ninput=nargin;
% NEXT TWO LINES TO ENUSRE THAT VARARGIN CAN BE PASSED TO FUNCTION
if ninput==2
% CALL USING VARARGIN
ninput=1+length(varargin{1});
varargin=varargin{1};
else
% DIRECT CALL
ninput=length(varargin);
end
% TRANSFORM VARARGING INTO PARAMETERS
cargin=1;
while (cargin<ninput)
if strcmp(varargin{cargin},'jump')
cargin=cargin+1;
eval(['jump=',num2str(varargin{cargin}),';']);
SegymatVerbose(['JUMP : Read only every ',num2str(jump),'th trace'])
end
if strcmp(varargin{cargin},'minmax')
cargin=cargin+1;
eval(['header=''',varargin{cargin},''';']);
cargin=cargin+1;
eval(['headermin=',num2str(varargin{cargin}),';']);
cargin=cargin+1;
eval(['headermax=',num2str(varargin{cargin}),';']);
SegymatVerbose(['MIN MAX : Using header ',header,' from ',num2str(headermin),' to ',num2str(headermax)])
end
if strcmp(varargin{cargin},'trange')
cargin=cargin+1;
eval(['tmin=',num2str(varargin{cargin}),';']);
cargin=cargin+1;
eval(['tmax=',num2str(varargin{cargin}),';']);
SegymatVerbose(['TRANGE : tmin=',num2str(tmin),' tmax=',num2str(tmax)])
end
if strcmp(varargin{cargin},'revision')
cargin=cargin+1;
eval(['revision=',num2str(varargin{cargin}),';']);
SegymatVerbose(['USING REVISION : rev=',num2str(revision)])
end
if strcmp(varargin{cargin},'dsf')
cargin=cargin+1;
eval(['dsf=',num2str(varargin{cargin}),';']);
SegymatVerbose(['USING Data Sample Format : dsf=',num2str(dsf)])
end
if strcmp(varargin{cargin},'SegyHeader')
cargin=cargin+1;
SegyHeader=varargin{cargin};
SegymatVerbose(['USING LOADED SEGYHEADER'])
end
% ENDIAN FORMAT
endian='ieee-be'; % Big Endian is default
if strcmp(varargin{cargin},'endian')
cargin=cargin+1;
eval(['endian_tight=varargin{cargin};'])
if endian_tight=='l',
SegymatVerbose(['USING LITTLE ENDIAN TYPE'])
endian='ieee-le';
else
SegymatVerbose(['USING BIG ENDIAN TYPE'])
end
end
cargin=cargin+1;
end
if exist('SkipData','var')==0,
SkipData=0; % [0] READ ONLY HEADER VALUES, [1] READ IN ALL DATA
end
if SkipData==1, SegymatVerbose(['Not reading data - headers only']), end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% TRY TO ESTIMATE NUMBER OF TRACES
if exist('endian')==1,
segyid = fopen(filename,'r',endian);
else
segyid = fopen(filename,'r','ieee-be'); % ALL DISK FILES ARE IN BIG
end % ENDIAN FORMAT, ACCORDING TO
% SEGY Y rev 1
SegyHeader=GetSegyHeader(segyid);
try
Revision=SegyHeader.SegyFormatRevisionNumber;
if Revision>0, Revision=1; end
if (SegyHeader.DataSampleFormat>length(SegyHeader.Rev(Revision+1).DataSampleFormat));
SegymatVerbose([mfilename,' : WARNING : YOU HAVE SELECTED (OR THE FILE IS FORMATTED SUCH THAT) A DATASAMPLE FORMAT THAT IS NOT DEFINED. \nREMEBER IEEE IS NOT SPECIFIED IN THE SEGY REV0 STANDARD !'])
if (Revision==0)
SegymatVerbose([mfilename,' : TRYING TO USE REVISION 1 AS OPPOSED TO REVISION 0'])
Revision=1;
if (SegyHeader.DataSampleFormat>length(SegyHeader.Rev(Revision+1).DataSampleFormat));
SegymatVerbose([mfilename,' : FATAL ERROR : STILL THE DATASAMPLE FORMAT IS NOT SUPPRTED - EXITING (Report error to [email protected])'])
else
SegymatVerbose([mfilename,' : APPARENT SUCCES CHANING FROM Revision 0 to 1 - Continuing'])
SegyHeader.SegyFormatRevisionNumber=1; % FORCING REVISION TO BE 1 !!!
end
end
end
FormatName=SegyHeader.Rev(Revision+1).DataSampleFormat(SegyHeader.DataSampleFormat).name;
Format=SegyHeader.Rev(Revision+1).DataSampleFormat(SegyHeader.DataSampleFormat).format;
BPS=SegyHeader.Rev(Revision+1).DataSampleFormat(SegyHeader.DataSampleFormat).bps;
txt=['SegyRevision ',sprintf('%0.4g',Revision),', ',FormatName,'(',num2str(SegyHeader.DataSampleFormat),')'];
fseek(segyid,0,'eof'); DataEnd=ftell(segyid);
DataStart=3600+3200*SegyHeader.NumberOfExtTextualHeaders;
fseek(segyid,DataStart,'bof'); % Go to the beginning of the file
fseek(segyid,DataStart,'bof'); % Go to the beginning of the file
SegyHeader.ntraces=(DataEnd-DataStart)./(240+(SegyHeader.ns)*(BPS/8));
catch
% could not estimate ntraces
end
fclose(segyid);
|
github
|
Abakumov/MLIB-master
|
ReadSegyTraceHeaderValue.m
|
.m
|
MLIB-master/OTHER/SegyMAT/ReadSegyTraceHeaderValue.m
| 4,675 |
utf_8
|
8f311e49d4b6b1593782814ec539cf0b
|
% ReadSegyTraceHeaderValue : Read a spedicifc trace header value
%
% Call:
% % By Name
% cdp=ReadSegyTraceHeaderValue(filename,'key','cdp');
% SourceX=ReadSegyTraceHeaderValue(filename,'key','SourceX');
% SourceY=ReadSegyTraceHeaderValue(filename,'key','SourceY');
%
% % By location in Trace Header
% SourceX=ReadSegyTraceHeaderValue(filename,'pos',72,'precision','int32');
%
% % Call 'TraceHeaderDef(1)' to see a list of TraceHeader 'key' names
%
% See also WriteSegyTraceHeaderValue, TraceHeaderDef
%
%
function hval=ReadSegyTraceHeaderValue(filename,varargin);%pos,type)
pos=0;
precision='int32';
ninput=nargin;
% TRANSFORM VARARGING INTO PARAMETERS
cargin=1;
while (cargin<ninput)
% ENDIAN FORMAT
endian='ieee-be'; % Big Endian is default
if strcmp(varargin{cargin},'endian')
cargin=cargin+1;
eval(['endian_tight=varargin{cargin};'])
if endian_tight=='l',
disp(['USING LITTLE ENDIAN TYPE'])
endian='ieee-le';
else
disp(['USING BIG ENDIAN TYPE'])
end
end
if strcmp(varargin{cargin},'pos')
cargin=cargin+1;
eval(['pos=',num2str(varargin{cargin}),';']);
disp(['Reading at header postision : pos=',num2str(pos+1)])
end
if strcmp(varargin{cargin},'precision')
cargin=cargin+1;
eval(['precision=''',varargin{cargin},''';']);
disp(['precision : ',precision])
end
if strcmp(varargin{cargin},'key')
cargin=cargin+1;
eval(['key=''',varargin{cargin},''';']);
STH=TraceHeaderDef;
try
pos=STH.(key).pos;
precision=STH.(key).precision;
catch
disp(sprintf('Trace Header Value %s not defined',key))
pos=0; precision='int32';
hval=[];
return
end
SegymatVerbose(sprintf('key=%s, startpos=%d, precision=%s ',key,pos+1,precision))
end
cargin=cargin+1;
end
if nargin<2
pos=0;
end
if nargin<3
type='int32';
end
if exist('endian')==1,
segyid = fopen(filename,'r',endian);
else
segyid = fopen(filename,'r','ieee-be'); % ALL DISK FILES ARE IN BIG
end % ENDIAN FORMAT, ACCORDING TO
[SegyHeader]=ReadSegyHeader(filename);
Revision=SegyHeader.SegyFormatRevisionNumber;
if Revision>0, Revision=1; end
if (SegyHeader.DataSampleFormat>length(SegyHeader.Rev(Revision+1).DataSampleFormat));
SegymatVerbose([mfilename,' : WARNING : YOU HAVE SELECTED (OR THE FILE IS FORMATTED SUCH THAT) A DATASAMPLE FORMAT THAT IS NOT DEFINED. \nREMEBER IEEE IS NOT SPECIFIED IN THE SEGY REV0 STANDARD !'])
if (Revision==0)
SegymatVerbose([mfilename,' : TRYING TO USE REVISION 1 AS OPPOSED TO REVISION 0'])
Revision=1;
if (SegyHeader.DataSampleFormat>length(SegyHeader.Rev(Revision+1).DataSampleFormat));
SegymatVerbose([mfilename,' : FATAL ERROR : STILL THE DATASAMPLE FORMAT IS NOT SUPPRTED - EXITING (Report error to [email protected])'])
else
SegymatVerbose([mfilename,' : APPARENT SUCCES CHANING FROM Revision 0 to 1 - Continuing'])
SegyHeader.SegyFormatRevisionNumber=1; % FORCING REVISION TO BE 1 !!!
end
end
end
FormatName=SegyHeader.Rev(Revision+1).DataSampleFormat(SegyHeader.DataSampleFormat).name;
Format=SegyHeader.Rev(Revision+1).DataSampleFormat(SegyHeader.DataSampleFormat).format;
BPS=SegyHeader.Rev(Revision+1).DataSampleFormat(SegyHeader.DataSampleFormat).bps;
txt=['SegyRevision ',sprintf('%0.4g',Revision),', ',FormatName,'(',num2str(SegyHeader.DataSampleFormat),')'];
%Revision=SegyHeader.SegyFormatRevisionNumber;
%if Revision>0, Revision=1; end
%FormatName=SegyHeader.Rev(Revision+1).DataSampleFormat(SegyHeader.DataSampleFormat).name;
%Format=SegyHeader.Rev(Revision+1).DataSampleFormat(SegyHeader.DataSampleFormat).format;
%BPS=SegyHeader.Rev(Revision+1).DataSampleFormat(SegyHeader.DataSampleFormat).bps;
%txt=['SegyRevision ',sprintf('%0.4g',Revision),',
%',FormatName,'(',num2str(SegyHeader.DataSampleFormat),')'];%
fseek(segyid,0,'eof'); DataEnd=ftell(segyid);
DataStart=3600+3200*SegyHeader.NumberOfExtTextualHeaders;
fseek(segyid,DataStart,'bof'); % Go to the beginning of the file
ntraces=(DataEnd-DataStart)./(240+(SegyHeader.ns)*(BPS/8));
hval=zeros(1,ntraces);
for itrace=1:ntraces
if ((itrace/10000)==round(itrace/10000))
progress_txt(itrace,ntraces,'Trace #')
end
%GOTO START OF TRACE HEADER
skip=DataStart+(itrace-1)*(240+(BPS/8)*SegyHeader.ns);
fseek(segyid,skip,'bof');
fseek(segyid,pos,'cof');
hval(itrace)=fread(segyid,1,precision);
end
fclose(segyid);
|
github
|
Abakumov/MLIB-master
|
wiggle.m
|
.m
|
MLIB-master/OTHER/SegyMAT/wiggle.m
| 6,108 |
utf_8
|
fa997a889c0e07b3fa641caad52d5f57
|
% wiggle : plot wiggle/VA/image plot
%
% Call
% wiggle(Data); % wiggle plot
% wiggle(Data,scale); % scaled wiggle plot
% wiggle(x,t,Data); % wiggle plt
% wiggle(x,t,Data,'VA') % variable Area (pos->black;neg->transp)
% wiggle(x,t,Data,'VA2') % variable Area (pos->black;neg->red)
% wiggle(x,t,Data,'wiggle',scale); % Scaled wiggle
% wiggle(x,t,Data,'wiggle',scale,showmax); % Scaled wiggle and max
% showmax traces.
% wiggle(x,t,Data,'wiggle',scale,showmax,plimage); % wiggle + image
% wiggle(x,t,Data,'wiggle',scale,showmax,plimage,caxis); % wiggle +
% scaled image
%
% Data : [nt,ntraces]
% x : [1:ntraces] X axis (ex [SegyTraceheaders.offset])
% t : [1:nt] Y axis
% style : ['VA'] : Variable Area
% ['wiggle'] : Wiggle plot
% scale : scaling factor, can be left empty as []
% showmax [scalar] : max number of traces to show on display [def=100]
% plimage [0/1] : Show image beneath wiggles [def=0];
% caxis [min max]/[scalar] : amplitude range for colorscale
%
%
% MAKE IT WORK FOR ANY X-AXIS !!!
%
%
%
% (C) 2001-2004, Thomas Mejer Hansen, [email protected]/[email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
%
%
function wiggle(x,t,Data,style,dmax,showmax,plImage,imageax,ax_order,lineColor,example_plot);
is_hold_on = ishold;
if (nargin==11);
np=3;
subplot(np,np,1); wiggle(Data);
subplot(np,np,2); wiggle(Data,dmax);
subplot(np,np,3); wiggle(x,t,Data);
subplot(np,np,4); wiggle(x,t,Data,style,dmax);
subplot(np,np,5); wiggle(x,t,Data,style,dmax,showmax);
subplot(np,np,6); wiggle(x,t,Data,style,dmax,showmax,plImage);
if isempty(dmax),
dmax=max(abs(Data(:)));
end
subplot(np,np,7); wiggle(x,t,Data,style,dmax,showmax,plImage,dmax./10);
return
end
showmax_def=100;
style_def='wiggle';
if nargin==1,
Data=x;
t=[1:1:size(Data,1)];
x=[1:1:size(Data,2)];
dmax=max(Data(:));
style=style_def;
showmax=showmax_def;
end
if nargin==2,
Data=x;
dmax=t;
t=[1:1:size(Data,1)];
x=[1:1:size(Data,2)];
style=style_def;
showmax=showmax_def;
end
if nargin==3,
style=style_def;
dmax=max(abs(Data(:)));
showmax=showmax_def;
end
if nargin==4,
dmax=max(abs(Data(:)));
showmax=showmax_def;
end
if nargin==5,
showmax=showmax_def;
end
if nargin<7
plImage=0;
end
if nargin<9
ax_order=1;
end
if nargin<10
lineColor=[0 0 0];
end
if isempty(dmax),
% Set scaling factor dmax if empty
dmax=max(abs(Data(:)));
end
if isempty(showmax),
showmax=100;
end
if nargin==7,
imageax=[-1 1].*dmax;
end
if plImage==1,
if ax_order==1;
imagesc(x,t,Data);
else
imagesc(t,x,Data');
end
if (length(imageax)==1)
imageax=[-1 1].*abs(imageax);
end
caxis(imageax);
hold on
end
if (showmax>0)
if length(x)>1,
dx=x(2)-x(1);
else
dx=1;
end
ntraces=length(x);
ntraces=size(Data,2);
d=ntraces/showmax;
if d<=1; d=1; end
d=round(d);
dmax=dmax/d;
LineWidth=0.0001;
EdgeColor=lineColor;
for i=1:d:ntraces
xt=dx*Data(:,i)'./dmax;
if (strmatch('VA',style)==1)
xt1=xt;xt1(find(xt1>0))=0;
xx=[xt,fliplr(xt1)];
tt=[t,fliplr(t)];
ii=find(~isnan(xx));
if ax_order==1;
f1=fill(x(i)+xx(ii),tt(ii),lineColor);
%f1=fill(x(i)+xx,tt,lineColor);
else
f1=fill(tt(ii),x(i)+xx(i),[lineColor]);
%f1=fill(tt,x(i)+xx,[lineColor]);
%f1=fill([t,fliplr(t)],x(i)+[xt,fliplr(xt1)],[lineColor]);
end
set(f1,'LineWidth',LineWidth)
set(f1,'EdgeColor',EdgeColor)
%set(f1,'EdgeAlpha',[0]); % GIVES ROCKY IMAGES
hold on
if (strmatch('VA2',style,'exact')==1)
xt2=xt;xt2(find(xt2<0))=0;
if ax_order==1;
f2=fill(x(i)+[xt,fliplr(xt2)],[t,fliplr(t)],[1 0 0]);
else
f2=fill([t,fliplr(t)],x(i)+[xt,fliplr(xt2)],[1 0 0]);
end
set(f2,'LineWidth',LineWidth)
set(f2,'EdgeColor',EdgeColor)
%set(f2,'EdgeAlpha',[0])
end
else
% MATLAB PLOT
if ax_order==1;
plot(xt+x(i),t,'-','linewidth',.05,'color',lineColor);
else
plot(t,xt+x(i),'-','linewidth',.05,'color',lineColor);
end
%OCTAVE PLOT
%plot(xt+x(i),t,'k-')
end
if i==1, hold on;end
end
end
hold off;
set(gca,'Ydir','reverse')
if is_hold_on==1
return;
end
try
if ax_order==1;
axis([min(x(1:ntraces))-(x(2)-x(1)) max(x(1:ntraces))+(x(2)-x(1)) min(t) max(t)])
else
axis([min(t) max(t) min(x)-(x(2)-x(1)) max(x)+(x(2)-x(1)) ])
end
catch
try
if ax_order==1;
axis([min(x) max(x) min(t) max(t)])
else
axis([min(t) max(t) min(x) max(x) ])
end
end
end
|
github
|
Abakumov/MLIB-master
|
PutSegyTrace.m
|
.m
|
MLIB-master/OTHER/SegyMAT/PutSegyTrace.m
| 9,299 |
utf_8
|
1fbee6bb87d268064255735d9f45c572
|
% PutSegyTrace(segyid,tracedata,SegyTraceHeader,TraceStart);
%
% Write a SegyTrace to a filehandle 'segyid'
%
% (C) 2001-2004, Thomas Mejer Hansen, [email protected]/[email protected]
%
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
%
function PutSegyTrace(segyid,tracedata,SegyTraceHeader,SegyHeader);
% *** DUE TO A BUG IN MATLAB 6.5 : Technical Solution Number: 31977
% Enable next line if error messages show that not all
% trace header values have been set.
% Enabling this check will considerably slow down writing
% with factor of about 6!
% SegyTraceHeader=CheckSegyTraceHeader(SegyTraceHeader);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% WRITE SegyTraceHeader
if ~exist('TraceStart')==1, TraceStart=ftell(segyid);end
fseek(segyid,0,'bof');fseek(segyid,TraceStart,'bof'); % ***
fwrite(segyid,ones(1,60),'int32');
fseek(segyid,0,'bof');fseek(segyid,TraceStart,'bof'); % ***
WRITETRACEHEADER=1;
if WRITETRACEHEADER==1,
fseek(segyid,0,'bof');
fseek(segyid,TraceStart,'bof');
fwrite(segyid,SegyTraceHeader.TraceSequenceLine,'int32'); % 0
fwrite(segyid,SegyTraceHeader.TraceSequenceFile,'int32'); % 4
fwrite(segyid,SegyTraceHeader.FieldRecord,'int32'); % 8
fwrite(segyid,SegyTraceHeader.TraceNumber,'int32'); % 12
fwrite(segyid,SegyTraceHeader.EnergySourcePoint,'int32'); % 16
fwrite(segyid,SegyTraceHeader.cdp,'int32'); % 20
fwrite(segyid,SegyTraceHeader.cdpTrace,'int32'); % 24
fwrite(segyid,SegyTraceHeader.TraceIdenitifactionCode,'int16'); % 28
fwrite(segyid,SegyTraceHeader.NSummedTraces,'int16'); % 30
fwrite(segyid,SegyTraceHeader.NStackedTraces,'int16'); % 32
fwrite(segyid,SegyTraceHeader.DataUse,'int16'); % 34
fwrite(segyid,SegyTraceHeader.offset,'int32'); %36
fwrite(segyid,SegyTraceHeader.ReceiverGroupElevation,'int32'); %40
fwrite(segyid,SegyTraceHeader.SourceSurfaceElevation,'int32'); %44
fwrite(segyid,SegyTraceHeader.SourceDepth,'int32'); %48
fwrite(segyid,SegyTraceHeader.ReceiverDatumElevation,'int32'); %52
fwrite(segyid,SegyTraceHeader.SourceDatumElevation,'int32'); %56
fwrite(segyid,SegyTraceHeader.SourceWaterDepth,'int32'); %60
fwrite(segyid,SegyTraceHeader.GroupWaterDepth,'int32'); %64
fwrite(segyid,SegyTraceHeader.ElevationScalar,'int16'); %68
% Multiply/divide next number for following 4 values
fwrite(segyid,SegyTraceHeader.SourceGroupScalar,'int16'); %70
fwrite(segyid,SegyTraceHeader.SourceX,'int32'); %72
fwrite(segyid,SegyTraceHeader.SourceY,'int32'); %76
fwrite(segyid,SegyTraceHeader.GroupX,'int32'); %80
fwrite(segyid,SegyTraceHeader.GroupY,'int32'); %84
fwrite(segyid,SegyTraceHeader.CoordinateUnits,'int16'); %88
fwrite(segyid,SegyTraceHeader.WeatheringVelocity,'int16'); %90
fwrite(segyid,SegyTraceHeader.SubWeatheringVelocity,'int16'); %92
fwrite(segyid,SegyTraceHeader.SourceUpholeTime,'int16'); %94
fwrite(segyid,SegyTraceHeader.GroupUpholeTime,'int16'); %96
fwrite(segyid,SegyTraceHeader.SourceStaticCorrection,'int16'); %98
fwrite(segyid,SegyTraceHeader.GroupStaticCorrection,'int16'); %100
fwrite(segyid,SegyTraceHeader.TotalStaticApplied,'int16'); %102
fwrite(segyid,SegyTraceHeader.LagTimeA,'int16'); %104
fwrite(segyid,SegyTraceHeader.LagTimeB,'int16'); %106
fwrite(segyid,SegyTraceHeader.DelayRecordingTime,'int16'); %108
fwrite(segyid,SegyTraceHeader.MuteTimeStart,'int16'); %110
fwrite(segyid,SegyTraceHeader.MuteTimeEND,'int16'); %112
fwrite(segyid,SegyTraceHeader.ns,'uint16'); %114
fwrite(segyid,SegyTraceHeader.dt,'uint16'); %116
fwrite(segyid,SegyTraceHeader.GainType,'int16'); %118
fwrite(segyid,SegyTraceHeader.InstrumentGainConstant,'int16'); %120
fwrite(segyid,SegyTraceHeader.InstrumentInitialGain,'int16'); %%122
fwrite(segyid,SegyTraceHeader.Correlated,'int16'); %124
fwrite(segyid,SegyTraceHeader.SweepFrequenceStart,'int16'); %126
fwrite(segyid,SegyTraceHeader.SweepFrequenceEnd,'int16'); %128
fwrite(segyid,SegyTraceHeader.SweepLength,'int16'); %130
fwrite(segyid,SegyTraceHeader.SweepType,'int16'); %132
fwrite(segyid,SegyTraceHeader.SweepTraceTaperLengthStart,'int16'); %134
fwrite(segyid,SegyTraceHeader.SweepTraceTaperLengthEnd,'int16'); %136
fwrite(segyid,SegyTraceHeader.TaperType,'int16'); %138
fwrite(segyid,SegyTraceHeader.AliasFilterFrequency,'int16'); %140
fwrite(segyid,SegyTraceHeader.AliasFilterSlope,'int16'); %142
fwrite(segyid,SegyTraceHeader.NotchFilterFrequency,'int16'); %144
fwrite(segyid,SegyTraceHeader.NotchFilterSlope,'int16'); %146
fwrite(segyid,SegyTraceHeader.LowCutFrequency,'int16'); %148
fwrite(segyid,SegyTraceHeader.HighCutFrequency,'int16'); %150
fwrite(segyid,SegyTraceHeader.LowCutSlope,'int16'); %152
fwrite(segyid,SegyTraceHeader.HighCutSlope,'int16'); %154
fwrite(segyid,SegyTraceHeader.YearDataRecorded,'int16'); %156
fwrite(segyid,SegyTraceHeader.DayOfYear,'int16'); %158
fwrite(segyid,SegyTraceHeader.HourOfDay,'int16'); %160
fwrite(segyid,SegyTraceHeader.MinuteOfHour,'int16'); %162
fwrite(segyid,SegyTraceHeader.SecondOfMinute,'int16'); %164
fwrite(segyid,SegyTraceHeader.TimeBaseCode,'int16'); %166
fwrite(segyid,SegyTraceHeader.TraceWeightningFactor,'int16'); %170
fwrite(segyid,SegyTraceHeader.GeophoneGroupNumberRoll1,'int16'); %172
fwrite(segyid,SegyTraceHeader.GeophoneGroupNumberFirstTraceOrigField,'int16'); %174
fwrite(segyid,SegyTraceHeader.GeophoneGroupNumberLastTraceOrigField,'int16'); %176
fwrite(segyid,SegyTraceHeader.GapSize,'int16'); %178
fwrite(segyid,SegyTraceHeader.OverTravel,'int16'); %178
fwrite(segyid,SegyTraceHeader.cdpX,'int32'); %180
fwrite(segyid,SegyTraceHeader.cdpY,'int32'); %184
fwrite(segyid,SegyTraceHeader.Inline3D,'int32'); %188
fwrite(segyid,SegyTraceHeader.Crossline3D,'int32'); %192
fwrite(segyid,SegyTraceHeader.ShotPoint,'int32'); %196
fwrite(segyid,SegyTraceHeader.ShotPointScalar,'int16'); %200
fwrite(segyid,SegyTraceHeader.TraceValueMeasurementUnit,'int16'); %202
fwrite(segyid,SegyTraceHeader.TransductionConstantMantissa,'int32'); %204
fwrite(segyid,SegyTraceHeader.TransductionConstantPower,'int16'); %208
fwrite(segyid,SegyTraceHeader.TransductionUnit,'int16'); %210
fwrite(segyid,SegyTraceHeader.TraceIdentifier,'int16'); %212
fwrite(segyid,SegyTraceHeader.ScalarTraceHeader,'int16'); %214
fwrite(segyid,SegyTraceHeader.SourceType,'int16'); %216
fwrite(segyid,SegyTraceHeader.SourceEnergyDirectionMantissa,'int32'); %218
fwrite(segyid,SegyTraceHeader.SourceEnergyDirectionExponent,'int16'); %222
fwrite(segyid,SegyTraceHeader.SourceMeasurementMantissa,'int32'); %224
fwrite(segyid,SegyTraceHeader.SourceMeasurementExponent,'int16'); %228
fwrite(segyid,SegyTraceHeader.SourceMeasurementUnit,'int16'); %230
% WRITE UNASSIGNED CHARACTERS FOR THE REST
fwrite(segyid,SegyTraceHeader.UnassignedInt1,'int32'); %232
fwrite(segyid,SegyTraceHeader.UnassignedInt2,'int32'); %236
%fwrite(segyid,zeros(1,4),'int16'); %230
end
% 217-240 Unassigned
% go to end of header
% Any of the nex to lines should work, with the first line being the fastest
fseek(segyid,0,'cof'); fseek(segyid,240-216,'cof');
% fseek(segyid,0,'bof'); fseek(segyid,TraceStart+240,'bof');
Revision=SegyHeader.SegyFormatRevisionNumber;
if Revision>0, Revision=1; end
Format=SegyHeader.Rev(Revision+1).DataSampleFormat(SegyHeader.DataSampleFormat).format;
BPS=SegyHeader.Rev(Revision+1).DataSampleFormat(SegyHeader.DataSampleFormat).bps;
SegymatVerbose([mfilename,' SegyRevision ',sprintf('%0.4g',Revision),', ',Format],3);
%% WRITE TRACE DATA;
if (strcmp(Format,'uint32')==1)|(strcmp(Format,'uint16')==1), % IBM FLOATING POINT
% CONVERT FROM FLOATING POINT
SegymatVerbose([mfilename,'Converting from IBM, DataFormat :',SegyHeader.DataSampleFormat],2);
tracedata=double(num2ibm(tracedata));
end;
if SegyHeader.FixedLengthTraceFlag
fwrite(segyid,tracedata,Format);
else
fwrite(segyid,tracedata(1:SegyTraceHeader.ns),Format);
end
|
github
|
Abakumov/MLIB-master
|
ReadSegyConstantTraceLength.m
|
.m
|
MLIB-master/OTHER/SegyMAT/ReadSegyConstantTraceLength.m
| 17,042 |
utf_8
|
2b6c828210cef02c1b87939f60a737dd
|
% ReadSegyConstantTraceLength : Reads a SEG Y rev 0/1 formatted file
% Assumes CONSTANT TRACE LENGTH
% which allows much faster code
%
% Call :
% [Data,SegyTraceHeaders,SegyHeader]=ReadSegyConstantTraceLength(filename);
%
% To read time slice 0.5<t<5 :
% [Data,SegyTraceHeaders,SegyHeader]=ReadSegy(filename,'trange',.5,3);
% Skip every 5th trace :
% [Data,SegyTraceHeaders,SegyHeader]=ReadSegy(filename,'jump',5);
% Read data in a CDP header range : 5000<cdp<5800 :
% (change cdp to any other valid TraceHeader value)
% [Data,SegyTraceHeaders,SegyHeader]=ReadSegy(filename,'minmax','cdp',5000,5800);
% Use several minmax entries
% [Data,SegyTraceHeaders,SegyHeader]=ReadSegy(filename,'minmax','cdp',5000,5800,'minmax','SourceX',10,20);
%
%
% Read from trace 13-18:
% [Data,SegyTraceHeaders,SegyHeader]=ReadSegy(filename,'trace',13:18);
% Read from trace 13-18 and 100-130:
% [Data,SegyTraceHeaders,SegyHeader]=ReadSegy(filename,'trace',[13:18,100:130]);
%
% SEG-Y format revision number can be '0' (1975) or
% '100' (similar to '1') (2002).
% By default the SEG-Y format revision number is read in the
% binary header, but this can be overruled using :
% [Data,SegyTraceHeaders,SegyHeader]=ReadSegy(filename,'revision',0);
%
% Read using a specific Data Sample Format :
% Rev 0, IBM FLOATING POINT
% [Data,SegyTraceHeaders,SegyHeader]=ReadSegy(filename,'revision',0,'dsf',1);
% Rev 1, IEEE FLOATING POINT
% [Data,SegyTraceHeaders,SegyHeader]=ReadSegy(filename,'revision',1,'dsf',5);
%
% A SegyHeader can be forced on the SEG-Y file using :
% [Data,SegyTraceHeaders,SegyHeader]=ReadSegy(filename,'SegyHeader',SegyHeader);
% The SegyHeader can be obtain by GetSegyHeader(segyfilename), and
% then edited.
%
% To read using little endian :
% [Data,SegyTraceHeaders,SegyHeader]=ReadSegy(filename,'endian','l');
%
% Combine any combination of the above
% [Data,SegyTraceHeaders,SegyHeader]=ReadSegy(filename,'jump',1,'minmax','cdp',5300,5400);
%
%
% Plot the data using e.g.
% imagesc([SegyTraceHeaders.cdp],SegyHeader.time,Data);
% wiggle([SegyTraceHeaders.TraceNumber],SegyHeader.time,Data);
%
% (C) 2003-2004, Thomas Mejer Hansen, [email protected]
%
% Implemented using the syntax of the SEG-Y revised format :
% SEGY-Y rev 0, SEG-Y rev 1 as described in
% http://seg.org/publications/tech-stand/
%
% Extended Textual Header is not yet tested
% If you would like it implemented, please send me an SEGY file with
% that sort of information, as well as a description of the segy file
%
%
% (C) 2001-2004, Thomas Mejer Hansen, [email protected]/[email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
%
%
%
%
% 0.1 : INitial Release
% 0.2 : Added SkipData var, to skip reading of data.
% 0.3 : May 01, 2002
% Added ability to read in ever 'jump' traces.
% Added ability to read in time range.
% Added abiliy to read in header range (ex. mincdp to maxcdp).
%
% TODO : WHEN READING ONLY PART OF DATASET MAKE SURE TO ADJUST THE SEGY
% HEADER ACCORDINGLY !!!!!!
function [Data,SegyTraceHeaders,SegyHeader]=ReadSegy(filename,varargin);
if isoctave
doWaitBar=0; % [1] show progress bar gui
mfilename='ReadSegy';
else
doWaitBar=1;
mfilename='ReadSegy';
end
dsf=[];
revision=[];
endian_tight=[];
tmin=[];tmax=[];
headermin=[];headermax=[];header=[];
jump=[];
SkipData=[];
%tracestart=[]; traceend=[];
trace=[];
SegymatVerbose([mfilename,' : reading ',filename])
if ~(exist(filename)==2'),
SegymatVerbose([mfilename,' : ', filename,' does not exist !'])
Data=[];SegyTraceHeaders=[];SegyHeader=[];HeaderInfo=[];
return
end
% IF ONLY 'filename', AND one outpuet HAS BEEN
% SPECIFIED AS IN/OUTPUT, THEN USE THE FAST
% ALGORITHM FOR READING.
if (nargin==1)&(nargout==1)
[Data]=ReadSegyFast(filename);
return
end
SegymatVerbose([mfilename,' - Checking Varargin'],90)
ninput=nargin;
% NEXT TWO LINES TO ENUSRE THAT VARARGIN CAN BE PASSED TO FUNCTION
if ninput==2
% CALL USING VARARGIN
ninput=1+length(varargin{1});
varargin=varargin{1};
else
% DIRECT CALL
ninput=length(varargin);
end
nmm=0;
% TRANSFORM VARARGING INTO PARAMETERS
cargin=1;
while (cargin<ninput)
SegymatVerbose([mfilename,' - Converting varargin, ',num2str(cargin)],90)
if strcmp(varargin{cargin},'jump')
cargin=cargin+1;
eval(['jump=',num2str(varargin{cargin}),';']);
SegymatVerbose(['JUMP : Read only every ',num2str(jump),'th trace'])
end
if strcmp(varargin{cargin},'trace')
cargin=cargin+1;
trace=varargin{cargin};
SegymatVerbose(sprintf('trace: reading %d from trace %d to %d',length(trace),min(trace),max(trace)));
end
if strcmp(varargin{cargin},'minmax')
nmm=nmm+1;
cargin=cargin+1;
eval(sprintf('header{%d}=''%s'';',nmm,varargin{cargin}))
cargin=cargin+1;
eval(sprintf('headermin(%d)=%f;',nmm,varargin{cargin}));
cargin=cargin+1;
eval(sprintf('headermax(%d)=%f;',nmm,varargin{cargin}));
SegymatVerbose(['MIN MAX : Using header ',header{nmm},' from ',num2str(headermin(nmm)),' to ',num2str(headermax(nmm))])
end
if strcmp(varargin{cargin},'trange')
cargin=cargin+1;
eval(['tmin=',num2str(varargin{cargin}),';']);
cargin=cargin+1;
eval(['tmax=',num2str(varargin{cargin}),';']);
SegymatVerbose(['TRANGE : tmin=',num2str(tmin),' tmax=',num2str(tmax)])
end
% ENDIAN FORMAT
endian='ieee-be'; % Big Endian is default
if strcmp(varargin{cargin},'endian')
cargin=cargin+1;
eval(['endian_tight=varargin{cargin};'])
if endian_tight=='l',
SegymatVerbose(['USING LITTLE ENDIAN TYPE'])
endian='ieee-le';
else
SegymatVerbose(['USING BIG ENDIAN TYPE'])
end
end
if strcmp(varargin{cargin},'revision')
cargin=cargin+1;
eval(['revision=',num2str(varargin{cargin}),';']);
SegymatVerbose(['USING REVISION : rev=',num2str(revision)])
end
if strcmp(varargin{cargin},'dsf')
cargin=cargin+1;
eval(['dsf=',num2str(varargin{cargin}),';']);
SegymatVerbose(['USING Data Sample Format : dsf=',num2str(dsf)])
end
if strcmp(varargin{cargin},'SkipData')
cargin=cargin+1;
eval(['SkipData=',num2str(varargin{cargin}),';']);
SegymatVerbose(['SKIPPING DATA - READING ONLY HEADERS'])
end
if strcmp(varargin{cargin},'SegyHeader')
cargin=cargin+1;
SegyHeader=varargin{cargin};
SegymatVerbose(['USING LOADED SEGYHEADER'])
end
cargin=cargin+1;
end
if isempty(SkipData)==1,
SegymatVerbose([mfilename,' : Skip data is not set (defautls to 0)'],90)
SkipData=0; % [0] READ ONLY HEADER VALUES, [1] READ IN ALL DATA
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% OPEN FILE HANDLE
if exist('endian')==1,
SegymatVerbose([mfilename,' : ENDIAN : ',endian],90)
segyid = fopen(filename,'r',endian);
else
endian='ieee-be';
SegymatVerbose([mfilename,' : ENDIAN SET TO ',endian],90)
segyid = fopen(filename,'r','ieee-be'); % ALL DISK FILES ARE IN BIG
end % ENDIAN FORMAT, ACCORDING TO
% SEGY Y rev 1
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% BINARY HEADERS
if exist('SegyHeader')==0
SegyHeader=GetSegyHeader(segyid);
else
SegymatVerbose([mfilename,' - Using supplied SegyHeader'])
end
% APPLY CHANGES TO SEGY HEADER IF NEEDE
if isempty(revision)==0,
SegyHeader.SegyFormatRevisionNumber=revision;
SegymatVerbose([mfilename,' - Manually set SEG-Y revision to ',num2str(revision)])
end
if isempty(dsf)==0,
SegyHeader.DataSampleFormat=dsf;
end
% JUST SOME INFORMATION TO WRITE TO SCREEN :
Revision=SegyHeader.SegyFormatRevisionNumber;
if Revision>0, Revision=1; end
if (SegyHeader.DataSampleFormat>length(SegyHeader.Rev(Revision+1).DataSampleFormat));
SegymatVerbose([mfilename,' : WARNING : YOU HAVE SELECTED (OR THE FILE IS FORMATTED SUCH THAT) A DATASAMPLE FORMAT THAT IS NOT DEFINED. \nREMEBER IEEE IS NOT SPECIFIED IN THE SEGY REV0 STANDARD !'])
if (Revision==0)
SegymatVerbose([mfilename,' : TRYING TO USE REVISION 1 AS OPPOSED TO REVISION 0'])
Revision=1;
if (SegyHeader.DataSampleFormat>length(SegyHeader.Rev(Revision+1).DataSampleFormat));
SegymatVerbose([mfilename,' : FATAL ERROR : STILL THE DATASAMPLE FORMAT IS NOT SUPPRTED - EXITING (Report error to [email protected])'])
else
SegymatVerbose([mfilename,' : APPARENT SUCCES CHANING FROM Revision 0 to 1 - Continuing'])
SegyHeader.SegyFormatRevisionNumber=1; % FORCING REVISION TO BE 1 !!!
end
end
end
FormatName=SegyHeader.Rev(Revision+1).DataSampleFormat(SegyHeader.DataSampleFormat).name;
Format=SegyHeader.Rev(Revision+1).DataSampleFormat(SegyHeader.DataSampleFormat).format;
BPS=SegyHeader.Rev(Revision+1).DataSampleFormat(SegyHeader.DataSampleFormat).bps;
txt=['SegyRevision ',sprintf('%0.4g',Revision),', ',FormatName,'(',num2str(SegyHeader.DataSampleFormat),')'];
ns=SegyHeader.ns;
% YOU CAN FORCE FixedLengthTraceFlag=1;
% This will make the code much faster (especially when using
% the 'jump' option) but reading data with varying trace lengt will fail.
% It is here since many old data sets with Constant trace length
% has FixedLengthTraceFlag=0;
%
% As of version 1.01 this has been enable by default.
% Change the variable below to '0' if you do not want this behaviour
%
SegyHeader.FixedLengthTraceFlag=1;
SegymatVerbose([mfilename,' : Reading Data'],90);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% READ DATA
%Segy=fread(segyid,4000,'float32');
fseek(segyid,0,'eof'); DataEnd=ftell(segyid);
fseek(segyid,0,'eof'); DataEnd=ftell(segyid);
DataStart=3600+3200*SegyHeader.NumberOfExtTextualHeaders;
fseek(segyid,DataStart,'bof'); % Go to the beginning of the file
fseek(segyid,DataStart,'bof'); % Go to the beginning of the file
ntraces=(DataEnd-DataStart)./(240+(SegyHeader.ns)*(BPS/8));
SegymatVerbose(['Number of Samples Per Trace=',num2str(SegyHeader.ns)])
SegymatVerbose(['Number of Traces=',num2str(ntraces)])
if (ntraces~=round(ntraces))
SegymatVerbose(['Trace lengths seems to vary. trying to read the file anyway'])
end
existJump=~isempty(jump);
existHeader=~isempty(header);
existTmin=~isempty(tmin);
existTmax=~isempty(tmax);
existTrace=~isempty(trace);
dwaitbar=1;
if DataEnd>1e+6, dwaitbar=10; end
if DataEnd>1e+7, dwaitbar=50; end
if DataEnd>1e+8, dwaitbar=200; end
traceinfile=0;
outtrace=0;
tic;
toc_old=toc;
% FIND TRACES TO USE
getTrace=1:1:ntraces;
if existTrace
% getTrace=tracestart:1:traceend;
getTrace=trace;
end
if nmm>0
allTraces=ones(1,ntraces);
for imm=1:nmm
val=ReadSegyTraceHeaderValue(filename,'key',header{imm});
badTraces=find((val<headermin(imm))|(val>headermax(imm)));
allTraces(badTraces)=0;
end
getTrace=find(allTraces);
end
if existJump==1
getTrace=getTrace(jump:jump:length(getTrace));
end
out_ntraces=length(getTrace);
% LOOP OVER TRACES
if doWaitBar==1;
hw=waitbar(0,['Reading Segy - ',txt]);
end
%while (~(ftell(segyid)>=DataEnd))
for traceinfile=1:length(getTrace);
usetrace=1; % DEFAULT USING TRACE WHEN [1].
ishow=500;
if ((traceinfile/ishow)==round(traceinfile/ishow)),
PerTrace=(toc-toc_old)/ishow;
TimeLeft=(out_ntraces-traceinfile)*PerTrace;
txt=sprintf('Reading trace %d/%d, (%5.0fs left)',traceinfile,out_ntraces,TimeLeft);
toc_old=toc;
SegymatVerbose(txt)
end
TraceStart=ftell(segyid);
TraceStart=DataStart+(getTrace(traceinfile)-1)*(SegyHeader.ns*BPS/8+240);
% if ((usetrace==0)&(SegyHeader.FixedLengthTraceFlag==1)),
% % SKIP FORWARD IN FILE'
% skip=240+(BPS/8)*SegyHeader.ns;
% fseek(segyid,skip,'cof');
% %SegymatVerbose([num2str(traceinfile),' - SKIPPING TRACE ... ',num2str(outtrace)])
% else
SingleSegyTraceHeaders=GetSegyTraceHeader(segyid,TraceStart,Format,SegyHeader.ns,[]);
SingleSegyData.data=GetSegyTraceData(segyid,SingleSegyTraceHeaders.ns,SegyHeader);
if SingleSegyTraceHeaders.TraceNumber<1
SingleSegyTraceHeaders.TraceNumber=traceinfile;
SegymatVerbose(sprintf('TraceNumber malformatetd. Setting TraceNumber=%d',traceinfile),10);
end
SegymatVerbose(sprintf('ns=%d, Trace in line : %d, Trace in file : %d, ns=%10.5f dt=%10.5f',SingleSegyTraceHeaders.ns,SingleSegyTraceHeaders.TraceSequenceLine,SingleSegyTraceHeaders.TraceSequenceFile,SingleSegyTraceHeaders.ns,SingleSegyTraceHeaders.dt),10)
%end
% % IF HEADER MIN MAX HAS BEEN CHOSEN, THEN CHECK THAT TRACE IS GOOD ENOUGH
% if ((existHeader==1)&(usetrace==1))
% headervalue=getfield(SingleSegyTraceHeaders,header);
% if ((headervalue<headermin)|(headervalue>headermax))
% usetrace=0;
% end
% end
% USE THIS TRACE IF usetrace=1 !!
if usetrace==1,
%% IF TIME RANGE IS SPECIFIED, THEN EXTRACT THIS
if (existTmin==1)&(existTmax==1)
% NEXT LINE SHOULD CONSIDER THAT ns in Trace and Segy Header could vary !!!
origtrange=[1:1:SegyHeader.ns].*SegyHeader.dt.*1e-6+SingleSegyTraceHeaders.DelayRecordingTime.*1e-3;
gooddata=find(origtrange>tmin & origtrange<tmax);
SingleSegyData.data=SingleSegyData.data(gooddata);
% CHECK NEXT LINE TAHT DelatRec... is in micro seconds
SingleSegyTraceHeaders.DelayRecordingTime=tmin;
SingleSegyTraceHeaders.ns=length(gooddata);
ns=length(gooddata); % for use below
end
outtrace=outtrace+1;
if (outtrace==1),
% Preallocate RAM
SegymatVerbose(sprintf('Pre allocating RAM ntraces=%d out_traces=%d',ntraces,out_ntraces));
SegyData=repmat(struct('data',zeros(ns,1)),1,out_ntraces);
SegyTraceHeaders=repmat(SingleSegyTraceHeaders,1,out_ntraces);
end
SegyData(outtrace).data=SingleSegyData.data;
SegyTraceHeaders(outtrace)=SingleSegyTraceHeaders;
if doWaitBar==1,
if ((outtrace/dwaitbar)==round(outtrace/dwaitbar))
waitbar(ftell(segyid)/DataEnd,hw);
end
end
end
end
if doWaitBar==1
close(hw);
end
SegymatVerbose([mfilename,' : Elapsed time ',num2str(toc)]);
t=outtrace;
% CHANGE SEGY HEADER IF TIME RANGE WAS SET
if (existTmin==1)&(existTmax==1)
SegyHeader.ns=ns;
SegyHeader.time=[1:1:SegyHeader.ns].*SegyHeader.dt./1e+6 + SegyTraceHeaders(1).DelayRecordingTime./1e+3;
end
% Make sure that only read SegyTraceHEaders are returned
if outtrace~=out_ntraces
SegyTraceHeaders=SegyTraceHeaders(1:outtrace);
end
SegyHeader.time=[1:1:SegyHeader.ns].*SegyHeader.dt./1e+6 + SegyTraceHeaders(1).DelayRecordingTime./1e+3;
% MOVE DATA from SegyData.data to a regular variable
if SkipData==1,
Data=[];
else
try
Data=[SegyData(1:outtrace).data];
catch
Data=zeros(ns,outtrace);
for i=1:outtrace
try
Data(:,i)=SegyData(i).data;
catch
errmsg=lasterr;
if isempty(SegyData(i).data)
errmsg='Empty data in trace';
elseif (strfind(errmsg, 'In an assignment A(:,matrix) = B, the number of rows in A and B'))
nns=length(SegyData(i).data);
if nns<ns
errmsg='Length of trace varies - padding with zeros';
Data(1:nns,i)=SegyData(i).data;
else
errmsg='Length of trace varies - truncating';
Data(:,i)=SegyData(i).data(1:ns);
end
end
SegymatVerbose(sprintf('Had a problem at trace %d : %s',i,errmsg))
end
end
end
end
|
github
|
Abakumov/MLIB-master
|
ReadSu.m
|
.m
|
MLIB-master/OTHER/SegyMAT/ReadSu.m
| 9,157 |
utf_8
|
a95043833515916c3ebcc28defa91252
|
% ReadSu : Reads a SU formatted file (Seismic Unix)
%
% Call :
% [Data,SuTraceHeaders,SuHeader]=ReadSu(filename);
%
% To read in big endian format (default):
% [Data,SuTraceHeaders,SuHeader]=ReadSu(filename,'endian','b');
% To read in little endian format :
% [Data,SuTraceHeaders,SuHeader]=ReadSu(filename,'endian','l');
%
%
% To read in trace data as 'int32' :
% [Data,SuTraceHeaders,SuHeader]=ReadSu(filename,'DataFormat','int32');
% To read time slice 0.5<t<5 :
% [Data,SuTraceHeaders,SuHeader]=ReadSu(filename,'trange',.5,3);
% Skip every 5th trace :
% [Data,SuTraceHeaders,SuHeader]=ReadSu(filename,'jump',5);
% Read data in a CDP header range : 5000<cdp<5800
% (change cdp to any other valid TraceHeader value)
% [Data,SuTraceHeaders,SuHeader]=ReadSu(filename,'minmax','cdp'5000,5800);
%
% Combine any combination of the above
% [Data,SuTraceHeaders,SuHeader]=ReadSu(filename,'jump',1,'minmax','cdp',5300,5400);
%
%
%
% (C) 2001-2004 Thomas Mejer Hansen, [email protected]/[email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
%
%
%
%
% 0.1 : INitial Release
% 0.2 : Added SkipData var, to skip reading of data.
% 0.3 : May 01, 2002
% Added ability to read in ever 'jump' traces.
% Added ability to read in time range.
% Added abiliy to read in header range (ex. mincdp to maxcdp).
%
function [Data,SuTraceHeaders,SuHeader]=ReadSu(filename,varargin);
dsf=[];
if ~(exist(filename)==2'),
SegymatVerbose([mfilename,' : ', filename,' does not exist !'])
Data=[];SuTraceHeaders=[];SuHeader=[];HeaderInfo=[];
return
end
% SET THE NEXT FLAG TO 1, IF YOU ARE SURE ALL TRACES HAVE THE SAME LENGT
% THIS WILL GREATLT INCREASE READING WHEN USING 'JUMP'
FixedTraceLength=1;
% NEXT TWO LINES TO ENUSRE THAT VARARGIN CAN BE PASSED TO FUNCTION
if nargin==2
% CALL USING VARARGIN
local_nargin=1+length(varargin{1});
varargin=varargin{1};
else
% DIRECT CALL
local_nargin=length(varargin);
end
%
% HERE SHOULD BE A CALL TO A DEFAULT SEGY HEADER !!!!
%
SegyHeader.SegyFormatRevisionNumber=1;
SegyHeader.DataSampleFormat=5;
SegyHeader.Rev=GetSegyHeaderBasics;
% TRANSFORM VARARGING INTO PARAMETERS
cargin=1;
while (cargin<local_nargin)
if strcmp(varargin{cargin},'endian')
cargin=cargin+1;
eval(['endian=char(varargin{cargin});']);
if strcmp(endian,'b'),SegymatVerbose(['Reading BIG ENDIAN STYLE']);end
if strcmp(endian,'l'),SegymatVerbose(['Reading LITTLE ENDIAN STYLE']);end
end
if strcmp(varargin{cargin},'DataFormat')
cargin=cargin+1;
eval(['DataFormat=char(varargin{cargin});'])
if strcmp(DataFormat,'float32'),
SegyHeader.DataSampleFormat=5; % IEEE
end
if strcmp(DataFormat,'int32'),
SegyHeader.DataSampleFormat=2; % 4 Byte, two's
% complement integer
end
if strcmp(DataFormat,'int16'),
SegyHeader.DataSampleFormat=3; % 2 Byte, two's
% complement integer
end
if strcmp(DataFormat,'int8'),
SegyHeader.DataSampleFormat=8; % 2 Byte, two's
% complement integer
end
SegymatVerbose(['DataFormat : ',num2str(SegyHeader.DataSampleFormat)])
end
if strcmp(varargin{cargin},'dsf')
cargin=cargin+1;
eval(['dsf=',num2str(varargin{cargin}),';']);
SegymatVerbose(['USING Data Sample Format : dsf=',num2str(dsf)])
end
if strcmp(varargin{cargin},'jump')
cargin=cargin+1;
eval(['jump=',num2str(varargin{cargin}),';']);
SegymatVerbose(['JUMP : Read only every ',num2str(jump),'th trace'])
end
if strcmp(varargin{cargin},'minmax')
cargin=cargin+1;
eval(['header=''',varargin{cargin},''';']);
cargin=cargin+1;
eval(['headermin=',num2str(varargin{cargin}),';']);
cargin=cargin+1;
eval(['headermax=',num2str(varargin{cargin}),';']);
SegymatVerbose(['MIN MAX : Using header ',header,' from ',num2str(headermin),' to ',num2str(headermax)])
end
if strcmp(varargin{cargin},'trange')
cargin=cargin+1;
eval(['tmin=',num2str(varargin{cargin}),';']);
cargin=cargin+1;
eval(['tmax=',num2str(varargin{cargin}),';']);
SegymatVerbose(['TRANGE : tmin=',num2str(tmin),' tmax=',num2str(tmax)])
end
cargin=cargin+1;
end
%
% MAYBE DATA FORMATS CAN VARY ?
% but for now we use float32 if nothing else is set
%
if exist('SegyHeader')==0,
SegyHeader.DataSampleFormat=5; % IEEE
end
if isempty(dsf)==0,
SegyHeader.DataSampleFormat=dsf;
end
%
% SU DATA CAN BE EITHER BIG OR SMALL ENDIAN
% DEFAULT IS BIG ENDIAN
%
if exist('endian')==0,
segyid = fopen(filename,'r'); % USE LOCAL BUTE ORDER AS DEFAULT
else
segyid = fopen(filename,'r',endian);
endian;
end
if ~(exist(filename)==2'),
SegymatVerbose([mfilename,' : ', filename,' does not exist !'])
Data=[];SegyTraceHeaders=[];SegyHeader=[];
return
end
if exist('SkipData','var')==0,
SkipData=0; % [0] READ ONLY HEADER VALUES, [1] READ IN ALL DATA
end
if SkipData==1, SegymatVerbose(['Not reading data - headers only']), end
% SEGY HEADER FORMAT INFO
Revision=SegyHeader.SegyFormatRevisionNumber;
if Revision>0, Revision=1; end
Format=SegyHeader.Rev(Revision+1).DataSampleFormat(SegyHeader.DataSampleFormat).name;
BPS=SegyHeader.Rev(Revision+1).DataSampleFormat(SegyHeader.DataSampleFormat).bps;
SegymatVerbose([mfilename,' : ',Format],2)
% GET SIZE OF FILE
fseek(segyid,0,'eof'); DataEnd=ftell(segyid);
fseek(segyid,0,'bof'); % Go to the beginning of the file
%txt=['SegyRevision ',sprintf('%0.4g',Revision),', ',Format,'(',num2str(SegyHeader.DataSampleFormat),')'];
txt=[Format,'(',num2str(SegyHeader.DataSampleFormat),')'];
%hw=waitbar(0,['Reading SU-file -',txt]);
traceinfile=0;
outtrace=0;
existJump=exist('jump');
existHeader=exist('header');
existtmin=exist('tmin');
existtmax=exist('tmax');
tic;
while (~(ftell(segyid)>=DataEnd))
traceinfile=traceinfile+1;
usetrace=1;
%if exist('jump')
if existJump==1;
if (traceinfile/jump)~=round(traceinfile/jump), usetrace=0; end
end
if ((usetrace==0)&(FixedTraceLength==1)&(exist('ns')==1))
skip=240+(SegyHeader.BytesPerSample/8)*ns;
fseek(segyid,skip,'cof');
else
% Read Trace Header
SingleSuTraceHeader=GetSegyTraceHeader(segyid);
ns=SingleSuTraceHeader.ns;
% IF HEADER MIN MAX HAS BEEN CHOSEN, THEN CHECK THAT TRACE IS GOOD ENOUGH
if ((existHeader==1)&(usetrace==1))
headervalue=getfield(SingleSuTraceHeader,header);
if ((headervalue<headermin)|(headervalue>headermax))
usetrace=0;
end
end
if usetrace==1;
% Read Segy Trace Data
SkipData=0;
else
SkipData=1;
end
SingleSuData.data=GetSegyTraceData(segyid,SingleSuTraceHeader.ns,SegyHeader,SkipData);
end % END READ TRACE OR NO FIXED LENGTH
if (usetrace==1)
%% IF TIME RANGE IS SPECIFIED, THEN EXTRACT THIS
if (existtmin)&(existtmax)
% NEXT LINE SHOULD CONSIDER THAT ns in Trace and Segy Header could vary !!!
origtrange=[1:1:SingleSuTraceHeader.ns].*SingleSuTraceHeader.dt./1e+6 + SingleSuTraceHeader.DelayRecordingTime./1e+3;
gooddata=find(origtrange>tmin & origtrange<tmax);
SingleSuData.data=SingleSuData.data(gooddata);
% CHECK NEXT LINE TAHT DelatRec... is in micro seconds
SingleSuTraceHeader.DelayRecordingTime=tmin;
SingleSuTraceHeader.ns=length(gooddata);
ns=length(gooddata); % for use below
end
outtrace=outtrace+1;
SuTraceHeaders(outtrace)=SingleSuTraceHeader;
SuData(outtrace).data=SingleSuData.data;
% keyboard
end
% waitbar(ftell(segyid)/DataEnd,hw);
end
%close(hw)
SegymatVerbose([mfilename,' : Elapsed time ',num2str(toc)],2);
ns=SuTraceHeaders(1).ns;
dt=SuTraceHeaders(1).dt;
nt=length(SuData);
% DefaultSegyHeader
SuHeader=SegyHeader;
SuHeader.ns=ns;
SuHeader.nsOrig=ns;
SuHeader.dt=dt;
SuHeader.dtOrig=dt;
SuHeader.FixedLengthTraceFlag=1; % CHECK THAT THIS IS TRUE
SuHeader.SegyFormatRevisionNumber=1;
SuHeader.NumberOfExtTextualHeaders=0;
Data=zeros(ns,nt);
try
for it=1:nt
Data(:,it)=SuData(it).data;
end
catch
SegymatVerbose([mfilename,' Could not collect data in one matrix - check byte order'])
end
%[HeaderInfo]=TraceheaderToInfo(SuTraceHeaders);
return
|
github
|
Abakumov/MLIB-master
|
Sac2Segy.m
|
.m
|
MLIB-master/OTHER/SegyMAT/Sac2Segy.m
| 7,218 |
utf_8
|
90b6976dc23355ecd2eecf8911bf0bba
|
% Sac2Segy : Reads SAC formatted data into a SegyMAT (SGY) structure
%
% CALL :
% [Data,SegyTraceHeader,SegyHeader]=Sac2Segy(files_in,segyfile_out,varargin)
%
% files_in : Either a single filename or a strcture of filenames
% files_in='d1.SAC';
% or
% files_in{1}='d1.SAC';
% files_in{2}='d2.SAC';
%
% Examples :
% [D,STH,SH]=Sac2Segy('','test.segy','FixedLengthTraceFlag',1);
% converts all SAC files into one SEGY file (test.segy), using
% a FixedLengthTraceFlag of 1. This is compatible with mosty
% any SEGY reader.
%
% [D,STH,SH]=Sac2Segy('','test.segy','FixedLengthTraceFlag',0);
% converts all SAC files into one SEGY file (test.segy), using
% a FixedLengthTraceFlag of 0, allowing varying trace length of SEGY files
% This is only compatible with revision 1 of the SEGY format.
%
% [D,STH,SH]=Sac2Segy('file.sac');
% convert file.sac to file.segy
%
% [D,STH,SH]=Sac2Segy('file.sac','another_file.segy');
% convert file.sac to another_file.segy
%
%
% Force little endian byte format for SAC file:
% Sac2Segy('file.sac','test.sgy','endian','l');
%
% Relies on sac2mat.m
%
% Download SAC files from : http://www.iris.edu/hq/ssn/events
%
function [Data,STH,SegyHeader]=Sac2Segy(files_in,segyfile_out,varargin)
endian='b'; % Default big endian SAC files
if nargin==0
d=dir('*.sac');
if (length(d)==0)
SegymatVerbose(sprintf('No SAC files found.',mfilename));
Data=[];STH=[];SegyHeader=[];
return
end
for i=1:length(d); files_in{i}=d(i).name;end
end
if nargin>0
if isempty(files_in)
d=dir('*.sac');
for i=1:length(d); files_in{i}=d(i).name;end
end
if (ischar(files_in)&(nargin==1))
[p,f,e]=fileparts(files_in);
segyfile_out=[f,'.segy'];
end
end
ninput=nargin;
% NEXT TWO LINES TO ENUSRE THAT VARARGIN CAN BE PASSED TO FUNCTION
if ninput==3
% CALL USING VARARGIN
ninput=2+length(varargin{1});
varargin=varargin{1};
else
% DIRECT CALL
ninput=length(varargin);
end
% TRANSFORM VARARGING INTO PARAMETERS
cargin=1;
while (cargin<ninput)
SegymatVerbose([mfilename,' - Converting varargin, ',varargin{cargin}],-1)
if strcmp(varargin{cargin},'FixedLengthTraceFlag')
cargin=cargin+1;
eval(['FixedLengthTraceFlag=',num2str(varargin{cargin}),';']);
SegymatVerbose(['FixedLengthTraceFlag = ',num2str(FixedLengthTraceFlag),'.'])
end
if strcmp(varargin{cargin},'endian')
cargin=cargin+1;
eval(['endian=''',(varargin{cargin}),''';']);
SegymatVerbose(['endian = ',endian,'.'])
end
cargin=cargin+1;
end
if exist('sac2mat.m','file')~=2
SegymatVerbose(['sac2mat needs to be in your path'],0)
SegymatVerbose(['Get it from http://mgstat.sourceforge.net/'],0)
return
end
try
[SACdata,SeisData] = sac2mat(files_in,endian);
catch MESS
if (strfind(MESS.message,'Out of memory'))
SegymatVerbose(['Out of memory error calling ''sac2mat'', suggesting endian type error'],0)
SegymatVerbose([' Try manyally setting the endian type'],0)
return
end
end
ntraces=size(SeisData,2);
ns=[SACdata.trcLen];
ns_max=max([SACdata.trcLen]);
data=size(ns_max,ntraces);
% GET dt
% ONE SHOULD MULTIPLY WITH 1e+6 USING SEGY FORMAT
% HOWEEVER SINCE DT IS WRITTEN IN
% UINT16 FORMAT, AND SAC DT IS
% USUALLY VERY HIGH WE MUST CHOOSE
% TO MULTIPLY ONLY WITH 1000.
for i=1:length(ns);
dt(i)=SACdata(i).times.delta.*1e+3;
end
% -------------------------------------------
% SET UP SegyHeader structure.
% -------------------------------------------
% IF A SPECFIC REVISION HAS BEEN CHOSEN, USE THAT
if exist('revision')==1,
if revision==1,
SegyHeader.SegyFormatRevisionNumber=100;
else
SegyHeader.SegyFormatRevisionNumber=0;
end
SegymatVerbose([mfilename,' : Using user specified SEG Y revision : ',num2str(revision)],1)
else
SegyHeader.SegyFormatRevisionNumber=100;
end
% IF A SPECFIC DATA SAMPLING FORMAT HAS BEEN SELECTED USE THAT
if exist('dsf')==1,
SegyHeader.DataSampleFormat=dsf;
SegymatVerbose([mfilename,' : Using user specified Data Sample Format : ',num2str(revision)],1)
else
SegyHeader.DataSampleFormat=5;
end
if exist('FixedLengthTraceFlag')==1,
SegyHeader.FixedLengthTraceFlag=FixedLengthTraceFlag;
else
if ntraces==1,
SegyHeader.FixedLengthTraceFlag=1;
else
if length(unique(ns))==1,
SegyHeader.FixedLengthTraceFlag=1;
else;
SegyHeader.FixedLengthTraceFlag=0;
end
end
end
%SegyHeader.FixedLengthTraceFlag=1;
SegyHeader.dt=dt(1);
SegyHeader.dtOrig=dt(1);
if exist('TextualFileHeader'), SegyHeader.TextualFileHeader=TextualFileHeader; end
if exist('Job')==1, SegyHeader.Job=Job; end;
if exist('Line')==1, SegyHeader.Line=Line; end
if exist('Reel')==1, SegyHeader.Reel=Reel; end
if exist('DataTracePerEnsemble')==1, SegyHeader.DataTracePerEnsemble=DataTracePerEnsemble; end
if exist('AuxiliaryTracePerEnsemble')==1, SegyHeader.AuxiliaryTracePerEnsemble=AuxiliaryTracePerEnsemble; end
if exist('ns')==1, SegyHeader.ns=ns(1); end
if exist('nsOrig')==1, SegyHeader.nsOrig=nsOrig(1); end
if exist('EnsembleFold')==1, SegyHeader.EnsembleFold=EnsembleFold; end
if exist('TraceSorting')==1, SegyHeader.TraceSorting=TraceSorting; end
if exist('VerticalSumCode')==1, SegyHeader.VerticalSumCode=VerticalSumCode; end
% -------------------------------------------
% SETUP SEGY TRACE HEADER
% -------------------------------------------
for i=1:ntraces;
if i==1,
STH(i)=InitSegyTraceHeader(ns(i),dt(i));
else
STH(i)=STH(1);
end
if SegyHeader.FixedLengthTraceFlag==1;
STH(i).ns=max(ns(i));
else
STH(i).ns=ns(i);
end
STH(i).TraceSequenceFile=i;
% EVENT DATA
STH(i).YearDataRecorded=SACdata(i).event.nzyear;
STH(i).DayOfYear=SACdata(i).event.nzjday;
STH(i).HourOfDay=SACdata(i).event.nzhour;
STH(i).MinuteOfHour=SACdata(i).event.nzmin;
STH(i).SecondOfMinut=SACdata(i).event.nzsec;
% TRIMES
try
STH(i).dt=dt(i);
catch
keyboard
end
% STATION DATA
STH(i).Inline3D=SACdata(i).station.stla;
STH(i).Crossline3D=SACdata(i).station.stlo;
STH(i).cdpX=SACdata(i).station.stla;
STH(i).cdpY=SACdata(i).station.stlo;
STH(i).ReceiverGroupElevation=SACdata(i).station.stel;
STH(i).ReceiverDatumElevation=SACdata(i).station.stel;
%SACdata(i).station.stdp
%SACdata(i).station.cmpaz
%SACdata(i).station.cmpinc
%SACdata(i).station.kstnm
%SACdata(i).station.kcmpnm
%SACdata(i).station.knetwk
Data(:,i)=SeisData(:,i);
%if ns(i)<max(ns)
% Data((ns(i)+1):max(ns),i)=NaN;
%end
end
if SegyHeader.FixedLengthTraceFlag==1;
ins=find(ns==max(ns));ins=ins(1);
SegyHeader.ns=ns(ins);
SegyHeader.dt=dt(ins);
for i=1:ntraces
STH(i).ns=ns(ins);
STH(i).dt=dt(ins);
end
end
% WRITE SEGY STRUCTURE IF REQUESTED
if ((nargin>1)|(exist('segyfile_out','var')))
SegyHeader=WriteSegyStructure(segyfile_out,SegyHeader,STH,Data);
end
|
github
|
Abakumov/MLIB-master
|
Segy2Su.m
|
.m
|
MLIB-master/OTHER/SegyMAT/Segy2Su.m
| 1,324 |
utf_8
|
98fec0641aadef465f1e04c141ade5a8
|
% Segy2Su : Converts SEGY file to SU format
%
% Call : Segy2Su(filename,ReadSegyOption)
% Replaces the filename suffix to '.su';
% 'ReadSegyOptions' are the same as to 'ReadSegy'
%
% See also : ReadSegy
%
%
%
% (C) 2001,2002 Thomas Mejer Hansen, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
%
%
function Segy2Su(filename,varargin);
[Data,SegyTraceHeaders,SegyHeader]=ReadSegy(filename,varargin);
SegyHeader.DataSampleFormat=5; % IEEE
SegyHeader.SegyFormatRevisionNumber=100; % SEGY REVISION 1
WriteSuStructure([filename,'.su'],SegyHeader,SegyTraceHeaders,Data);
|
github
|
Abakumov/MLIB-master
|
TraceHeaderDef.m
|
.m
|
MLIB-master/OTHER/SegyMAT/TraceHeaderDef.m
| 6,916 |
utf_8
|
52f7626e5608eec64237078b2941a280
|
% TraceHeaderDef : Defines names, position, and precision for Trace Headers
%
% % To get a Matlab structure with trace header definitions call:
% STH==TraceHeaderDef;
% % To get a list fo trace header definision listed on the screen call:
% STH==TraceHeaderDef(1)
%
% See also: ReadSegyTraceHeaderValue, WriteSegyTraceHeaderValue
%
function STH=TraceHeaderDef(print);
if nargin>0
STH=TraceHeaderDef;
fn=fieldnames(STH);
disp(sprintf('%4s %6s %s','POS','PREC','Traece Header Name'))
for i=1:length(fn)
disp(sprintf('%4d %6s %s',STH.(fn{i}).pos,STH.(fn{i}).precision,fn{i}))
end
return
end
%NEW
STH.TraceSequenceLine.pos=0; STH.TraceSequenceLine.precision='int32';
STH.TraceSequenceFile.pos=4; STH.TraceSequenceFile.precision='int32';
STH.FieldRecord.pos=8; STH.FieldRecord.precision='int32';
STH.TraceNumber.pos=12; STH.TraceNumber.precision='int32';
STH.EnergySourcePoint.pos=16;STH.EnergySourcePoint.precision='int32';
STH.cdp.pos=20; STH.cdp.precision='int32';
STH.cdpTrace.pos=24; STH.cdpTrace.precision='int32';
STH.TraceIdenitifactionCode.pos=28;STH.TraceIdenitifactionCode.precision='int16';
STH.NSummedTraces.pos=30; STH.NSummedTraces.precision='int16';
STH.NStackedTraces.pos=32; STH.NStackedTraces.precision='int16';
STH.DataUse.pos=34; STH.DataUse.precision='int16';
STH.offset.pos=36;STH.offset.precision='int32';
STH.ReceiverGroupElevation.pos=40;STH.ReceiverGroupElevation.precision='int32';
STH.SourceSurfaceElevation.pos=44;STH.SourceSurfaceElevation.precision='int32';
STH.SourceDepth.pos=48;STH.SourceDepth.precision='int32';
STH.ReceiverDatumElevation.pos=52;STH.ReceiverDatumElevation.precision='int32';
STH.SourceDatumElevation.pos=56;STH.SourceDatumElevation.precision='int32';
STH.SourceWaterDepth.pos=60;STH.SourceWaterDepth.precision='int32';
STH.GroupWaterDepth.pos=64;STH.GroupWaterDepth.precision='int32';
STH.ElevationScalar.pos=68;STH.ElevationScalar.precision='int16';
STH.SourceGroupScalar.pos=70;STH.SourceGroupScalar.precision='int16';
STH.SourceX.pos=72;STH.SourceX.precision='int32';
STH.SourceY.pos=76;STH.SourceY.precision='int32';
STH.GroupX.pos=80;STH.GroupX.precision='int32';
STH.GroupY.pos=84;STH.GroupY.precision='int32';
STH.CoordinateUnits.pos=88;STH.CoordinateUnits.precision='int16';
STH.WeatheringVelocity.pos=90;STH.WeatheringVelocity.precision='int16';
STH.SubWeatheringVelocity.pos=92;STH.SubWeatheringVelocity.precision='int16';
STH.SourceUpholeTime.pos=94;STH.SourceUpholeTime.precision='int16';
STH.GroupUpholeTime.pos=96;STH.GroupUpholeTime.precision='int16';
STH.SourceStaticCorrection.pos=98;STH.SourceStaticCorrection.precision='int16';
STH.GroupStaticCorrection.pos=100;STH.GroupStaticCorrection.precision='int16';
STH.TotalStaticApplied.pos=102;STH.TotalStaticApplied.precision='int16';
STH.LagTimeA.pos=104;STH.LagTimeA.precision='int16';
STH.LagTimeB.pos=106;STH.LagTimeB.precision='int16';
STH.DelayRecordingTime.pos=108;STH.DelayRecordingTime.precision='int16';
STH.MuteTimeStart.pos=110;STH.MuteTimeStart.precision='int16';
STH.MuteTimeEND.pos=112;STH.MuteTimeEND.precision='int16';
STH.ns.pos=114;STH.ns.precision='uint16';
STH.dt.pos=116;STH.dt.precision='uint16';
STH.GainType.pos=118;STH.GainType.precision='int16';
STH.InstrumentGainConstant.pos=120;STH.InstrumentGainConstant.precision='int16';
STH.InstrumentInitialGain.pos=122;STH.InstrumentInitialGain.precision='int16';
STH.Correlated.pos=124;STH.Correlated.precision='int16';
STH.SweepFrequenceStart.pos=126;STH.SweepFrequenceStart.precision='int16';
STH.SweepFrequenceEnd.pos=128;STH.SweepFrequenceEnd.precision='int16';
STH.SweepLength.pos=130;STH.SweepLength.precision='int16';
STH.SweepType.pos=132;STH.SweepType.precision='int16';
STH.SweepTraceTaperLengthStart.pos=134;STH.SweepTraceTaperLengthStart.precision='int16';
STH.SweepTraceTaperLengthEnd.pos=136;STH.SweepTraceTaperLengthEnd.precision='int16';
STH.TaperType.pos=138;STH.TaperType.precision='int16';
STH.AliasFilterFrequency.pos=140;STH.AliasFilterFrequency.precision='int16';
STH.AliasFilterSlope.pos=142;STH.AliasFilterSlope.precision='int16';
STH.NotchFilterFrequency.pos=144;STH.NotchFilterFrequency.precision='int16';
STH.NotchFilterSlope.pos=146;STH.NotchFilterSlope.precision='int16';
STH.LowCutFrequency.pos=148;STH.LowCutFrequency.precision='int16';
STH.HighCutFrequency.pos=150;STH.HighCutFrequency.precision='int16';
STH.LowCutSlope.pos=152;STH.LowCutSlope.precision='int16';
STH.HighCutSlope.pos=154;STH.HighCutSlope.precision='int16';
STH.YearDataRecorded.pos=156;STH.YearDataRecorded.precision='int16';
STH.DayOfYear.pos=158;STH.DayOfYear.precision='int16';
STH.HourOfDay.pos=160;STH.HourOfDay.precision='int16';
STH.MinuteOfHour.pos=162;STH.MinuteOfHour.precision='int16';
STH.SecondOfMinute.pos=164;STH.SecondOfMinute.precision='int16';
STH.TimeBaseCode.pos=166;STH.TimeBaseCode.precision='int16';
%STH.TimeBaseCodeText.pos=168;STH.TimeBaseCodeText.precision='int16';
STH.TraceWeightningFactor.pos=168;STH.TraceWeightningFactor.precision='int16';
STH.GeophoneGroupNumberRoll1.pos=170;STH.GeophoneGroupNumberRoll1.precision='int16';
STH.GeophoneGroupNumberFirstTraceOrigField.pos=172;STH.GeophoneGroupNumberFirstTraceOrigField.precision='int16';
STH.GeophoneGroupNumberLastTraceOrigField.pos=174;STH.GeophoneGroupNumberLastTraceOrigField.precision='int16';
STH.GapSize.pos=176;STH.GapSize.precision='int16';
STH.OverTravel.pos=178;STH.OverTravel.precision='int16';
STH.cdpX.pos=180;STH.cdpX.precision='int32';
STH.cdpY.pos=184;STH.cdpY.precision='int32';
STH.Inline3D.pos=188;STH.Inline3D.precision='int32';
STH.Crossline3D.pos=192;STH.Crossline3D.precision='int32';
STH.ShotPoint.pos=196;STH.ShotPoint.precision='int32';
STH.ShotPointScalar.pos=200;STH.ShotPointScalar.precision='int16';
STH.TraceValueMeasurementUnit.pos=202;STH.TraceValueMeasurementUnit.precision='int16';
STH.TransductionConstantMantissa.pos=204;STH.TransductionConstantMantissa.precision='int32';
STH.TransductionConstantPower.pos=208;STH.TransductionConstantPower.precision='int16';
STH.TransductionUnit.pos=210;STH.TransductionUnit.precision='int16';
STH.TraceIdentifier.pos=212;STH.TraceIdentifier.precision='int16';
STH.ScalarTraceHeader.pos=214;STH.ScalarTraceHeader.precision='int16';
STH.SourceType.pos=216;STH.SourceType.precision='int16';
STH.SourceEnergyDirectionMantissa.pos=218;STH.SourceEnergyDirectionMantissa.precision='int32';
STH.SourceEnergyDirectionExponent.pos=222;STH.SourceEnergyDirectionExponent.precision='int16';
STH.SourceMeasurementMantissa.pos=224;STH.SourceMeasurementMantissa.precision='in32';
STH.SourceMeasurementExponent.pos=228;STH.SourceMeasurementExponent.precision='int16';
STH.SourceMeasurementUnit.pos=230;STH.SourceMeasurementUnit.precision='int16';
STH.UnassignedInt1.pos=232;STH.UnassignedInt1.precision='int32';
STH.UnassignedInt2.pos=236;STH.UnassignedInt2.precision='int32';
|
github
|
Abakumov/MLIB-master
|
pick_line.m
|
.m
|
MLIB-master/OTHER/SegyMAT/pick_line.m
| 1,114 |
utf_8
|
ce24743d8bf8948986ac55954d092e10
|
% pick_line : pick a line from a figure;
%
%
% Based on doc(ginput);
function [xy,xys]=pick_line(name,LineWidth,LineColor);
if nargin<1, name='line';end
if nargin<2, LineWidth=3;end
if nargin<3, LineColor=[1 1 0];end
hold on
% Initially, the list of points is empty.
xy = [];
n = 0;
% Loop, picking up the points.
disp('Left mouse button picks points.')
disp('Right mouse button picks last point.')
but = 1;
while but == 1
[xi,yi,but] = ginput(1);
n = n+1;
xy(:,n) = [xi;yi];
if n ==1;
p=plot(xy(1),xy(2),'-','LineWidth',LineWidth,'Color',LineColor);
p_point=plot(xy(1),xy(2),'*','LineWidth',LineWidth,'Color',LineColor);
else
set(p_point,'Xdata',xy(1,:));
set(p_point,'Ydata',xy(2,:));
try
%SPLINE INTERPOLATION
t = 1:n;
ts = 1: 0.1: n;
xys = spline(t,xy,ts);
set(p,'Xdata',xys(1,:));
set(p,'Ydata',xys(2,:));
% p=plot(xy(1,:),xy(2,:),'w-');
end
end
drawnow;
%plot(xi,yi,'ro')
end
hold off
eval(sprintf('save %s.mat xy xys',name));
|
github
|
Abakumov/MLIB-master
|
SegymatVerbose.m
|
.m
|
MLIB-master/OTHER/SegyMAT/SegymatVerbose.m
| 1,283 |
utf_8
|
91cbd5d1f9f24c536b01898b26f34abc
|
% SegymatVerbose : Writes out verbose information to the screen
%
%
% Call :
% SegymatVerbose(text,verboselevel)
% prints out 'text' to screen if verboselevel is higher than threshold
% set in m-file.
%
%
% (C) 2001-2004, Thomas Mejer Hansen, [email protected]/[email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function SegymatVerbose(txt,level)
if nargin==0, return, end
if nargin==1,
level=1;
end
VerboseLevel=0;
% Only print information if at or above VerboseLevel
if level<=VerboseLevel
disp(sprintf('%s : %s','SegyMAT',txt))
end
|
github
|
Abakumov/MLIB-master
|
GetSegyTrace.m
|
.m
|
MLIB-master/OTHER/SegyMAT/GetSegyTrace.m
| 1,451 |
utf_8
|
608945ce44ea32a93854854871a745d6
|
% GetSegyTrace : Reads a seg y trace, data and header
%
% [SegyTraceHeader,SegyData]=GetSegyTrace(segyid,TraceStart,DataFormat,ns);
%
%
% (C) 2001-2004 Thomas Mejer Hansen, [email protected]/[email protected]
%
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
%
function [SegyTraceHeader,SegyData]=GetSegyTrace(segyid,TraceStart,DataFormat,ns,SegyTraceHeader);
if exist('DataFormat')==0, DataFormat='float32'; end
if exist('TraceStart')==0, TraceStart=ftell(segyid); end
if exist('SegyTraceHeader')
if isempty('SegyTraceHeader');
clear SegyTraceHeader;
end
end
[SegyTraceHeader]=GetSegyTraceHeader(segyid,TraceStart,DataFormat,ns);
[SegyTraceData]=GetSegyDataTraceHeader(segyid,TraceStart,DataFormat,ns);
|
github
|
Abakumov/MLIB-master
|
GetSegyHeaderBasics.m
|
.m
|
MLIB-master/OTHER/SegyMAT/GetSegyHeaderBasics.m
| 10,069 |
utf_8
|
a67e7faf59ac5e11643ce57a27675272
|
% GetSegyHeaderBasics : Default Segy Header Header settings
%
% Call :
% Rev=GetSegyHeaderBasics
%
%
%
% (C) 2001-2004, Thomas Mejer Hansen, [email protected]/[email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
%
function Rev=GetSegyHeaderBasics;
%
% TODO
% Fixed Point ???
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Revision 0
Rev(1).name='Revision 0 (1975)';
Rev(1).SegyFormatRevisionNumber=0;
% DataSampleFormat
Rev(1).DataSampleFormat(1).name='4-byte IBM Floating Point';
Rev(1).DataSampleFormat(2).name='4-byte Fixed Point - (UNSUPPORTED)';
Rev(1).DataSampleFormat(3).name='2-byte Fixed Point - (UNSUPPORTED)';
Rev(1).DataSampleFormat(4).name='4-byte Fixed Point with gain - (UNSUPPORTED)';
Rev(1).DataSampleFormat(1).format='uint32'; %
Rev(1).DataSampleFormat(2).format='int32'; %
Rev(1).DataSampleFormat(3).format='int16'; %
%Rev(1).DataSampleFormat(2).format=''; % 'uint32'; %
%Rev(1).DataSampleFormat(3).format=''; % 'uint16'; %
Rev(1).DataSampleFormat(4).format=''; % 'uint32'; %
Rev(1).DataSampleFormat(1).bps=32;
Rev(1).DataSampleFormat(2).bps=32;
Rev(1).DataSampleFormat(3).bps=16;
%Rev(1).DataSampleFormat(4).bps=32;
%Rev(1).DataSampleFormat(3).bps=0; % NOT IMPLEMENETD
Rev(1).DataSampleFormat(4).bps=0; % NOT IMPLEMENETD
% TraceSorting
Rev(1).TraceSorting(1).name='as recorded (no sorting)';
Rev(1).TraceSorting(2).name='CDP ensemble';
Rev(1).TraceSorting(3).name='single fold continous profile';
Rev(1).TraceSorting(4).name='horizontally stacked';
Rev(1).TraceSorting(1).value=1;
Rev(1).TraceSorting(2).value=2;
Rev(1).TraceSorting(3).value=3;
Rev(1).TraceSorting(4).value=4;
% SweepType
Rev(1).SweepType(1).value=1;
Rev(1).SweepType(1).name='Linear';
Rev(1).SweepType(2).value=2;
Rev(1).SweepType(2).name= 'Parabolic';
Rev(1).SweepType(3).value=3;
Rev(1).SweepType(3).name='Exponential';
Rev(1).SweepType(4).value=4;
Rev(1).SweepType(4).name= 'Other';
% TaperType
Rev(1).TaperType(1).value=1;
Rev(1).TaperType(1).name='Linear';
Rev(1).TaperType(2).value=2;
Rev(1).TaperType(2).name= 'Cos2';
Rev(1).TaperType(3).value=3;
Rev(1).TaperType(3).name='Other';
% CorrelatedDataTraces
Rev(1).CorrelatedDataTraces(1).value=1;
Rev(1).CorrelatedDataTraces(1).name='No';
Rev(1).CorrelatedDataTraces(2).value=2;
Rev(1).CorrelatedDataTraces(2).name= 'Yes';
% BinaryGain
Rev(1).BinaryGain(1).value=1;
Rev(1).BinaryGain(1).name='Yes';
Rev(1).BinaryGain(2).value=2;
Rev(1).BinaryGain(2).name= 'No';
% AmplitudeRecoveryMethod
Rev(1).AmplitudeRecoveryMethod(1).value=1;
Rev(1).AmplitudeRecoveryMethod(1).name='none';
Rev(1).AmplitudeRecoveryMethod(2).value=2;
Rev(1).AmplitudeRecoveryMethod(2).name= 'Spherical Divergence';
Rev(1).AmplitudeRecoveryMethod(3).value=3;
Rev(1).AmplitudeRecoveryMethod(3).name= 'AGC';
Rev(1).AmplitudeRecoveryMethod(4).value=4;
Rev(1).AmplitudeRecoveryMethod(4).name= 'Other';
% MeasurementSystem
Rev(1).MeasurementSystem(1).value=1;
Rev(1).MeasurementSystem(1).name='Meters';
Rev(1).MeasurementSystem(2).value=2;
Rev(1).MeasurementSystem(2).name= 'Feets';
% ImpulseSignalPolarity
Rev(1).ImpulseSignalPolarity(1).value=1;
Rev(1).ImpulseSignalPolarity(1).name='Negative number';
Rev(1).ImpulseSignalPolarity(2).value=2;
Rev(1).ImpulseSignalPolarity(2).name= 'Positive Number';
% VibratoryPolarityCode
Rev(1).VibratoryPolarityCode(1).value=1;
Rev(1).VibratoryPolarityCode(1).name='337.5 - 22.5';
Rev(1).VibratoryPolarityCode(2).value=2;
Rev(1).VibratoryPolarityCode(2).name= '22.5-67.5';
Rev(1).VibratoryPolarityCode(3).value=3;
Rev(1).VibratoryPolarityCode(3).name= '67.5-112.5';
Rev(1).VibratoryPolarityCode(4).value=4;
Rev(1).VibratoryPolarityCode(4).name= '112.5-157.5';
Rev(1).VibratoryPolarityCode(5).value=5;
Rev(1).VibratoryPolarityCode(5).name= '157.5-202.5';
Rev(1).VibratoryPolarityCode(6).value=6;
Rev(1).VibratoryPolarityCode(6).name= '202.5-247.5';
Rev(1).VibratoryPolarityCode(7).value=7;
Rev(1).VibratoryPolarityCode(7).name= '247.5-292.5';
Rev(1).VibratoryPolarityCode(8).value=8;
Rev(1).VibratoryPolarityCode(8).name= '292.5-337.5';
% FixedLengthTraceFlag
Rev(1).FixedLengthTraceFlag(1).value=0;
Rev(1).FixedLengthTraceFlag(1).name='Varying Trace Length';
Rev(1).FixedLengthTraceFlag(2).value=1;
Rev(1).FixedLengthTraceFlag(2).name= 'Fixed Trace Length';
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Revision 1
Rev(2).name='Revision 1 (2002)';
Rev(2).SegyFormatRevisionNumber=100;
% DataSampleFormat
Rev(2).DataSampleFormat(1).format='uint32'; %
Rev(2).DataSampleFormat(2).format='int32'; %
Rev(2).DataSampleFormat(3).format='int16'; %
Rev(2).DataSampleFormat(4).format=''; %
Rev(2).DataSampleFormat(5).format='float32'; %
Rev(2).DataSampleFormat(6).format=''; %
Rev(2).DataSampleFormat(7).format=''; %
Rev(2).DataSampleFormat(8).format='int8'; %
Rev(2).DataSampleFormat(1).bps=32;
Rev(2).DataSampleFormat(2).bps=32;
Rev(2).DataSampleFormat(3).bps=16;
Rev(2).DataSampleFormat(4).bps=0;
Rev(2).DataSampleFormat(5).bps=32;
Rev(2).DataSampleFormat(6).bps=0;
Rev(2).DataSampleFormat(7).bps=0;
Rev(2).DataSampleFormat(8).bps=8;
Rev(2).DataSampleFormat(1).name='4-byte IBM Floating Point';
Rev(2).DataSampleFormat(2).name='4-byte two''s complement';
Rev(2).DataSampleFormat(3).name='2-byte two''s complement';
Rev(2).DataSampleFormat(4).name='4-byte fixed-point with gain (obsolete) - NOT IMPLEMENTED';
Rev(2).DataSampleFormat(5).name='4-byte IEEE floating-point';
Rev(2).DataSampleFormat(6).name='DSF Not currently used';
Rev(2).DataSampleFormat(7).name='DSF Not currently used';
Rev(2).DataSampleFormat(8).name='1-byte, two''s complement integer';
% TraceSorting
Rev(2).TraceSorting(1).value=-1;
Rev(2).TraceSorting(1).name='Other (should be explained in user Extended Textual File Header stanza)';
Rev(2).TraceSorting(2).value=0;
Rev(2).TraceSorting(2).name= 'Unknown';
Rev(2).TraceSorting(3).value=1;
Rev(2).TraceSorting(3).name= 'As recorded (no sorting)';
Rev(2).TraceSorting(4).value=2;
Rev(2).TraceSorting(4).name= 'CDP ensemble';
Rev(2).TraceSorting(5).value=3;
Rev(2).TraceSorting(5).name= 'Single fold continuous profile';
Rev(2).TraceSorting(6).value=4;
Rev(2).TraceSorting(6).name= 'Horizontally stacked';
Rev(2).TraceSorting(7).value=5;
Rev(2).TraceSorting(7).name= 'Common source';
Rev(2).TraceSorting(8).value=6;
Rev(2).TraceSorting(8).name= 'Common receiver';
Rev(2).TraceSorting(9).value=7;
Rev(2).TraceSorting(9).name= 'Common offset';
Rev(2).TraceSorting(10).value=8;
Rev(2).TraceSorting(10).name= 'Common mid-point';
% SweepType
Rev(2).SweepType(1).value=1;
Rev(2).SweepType(1).name='Linear';
Rev(2).SweepType(2).value=2;
Rev(2).SweepType(2).name= 'Parabolic';
Rev(2).SweepType(3).value=3;
Rev(2).SweepType(3).name='Exponential';
Rev(2).SweepType(4).value=4;
Rev(2).SweepType(4).name= 'Other';
% TaperType
Rev(2).TaperType(1).value=1;
Rev(2).TaperType(1).name='Linear';
Rev(2).TaperType(2).value=2;
Rev(2).TaperType(2).name= 'Cos2';
Rev(2).TaperType(3).value=3;
Rev(2).TaperType(3).name='Other';
% CorrelatedDataTraces
Rev(2).CorrelatedDataTraces(1).value=1;
Rev(2).CorrelatedDataTraces(1).name='No';
Rev(2).CorrelatedDataTraces(2).value=2;
Rev(2).CorrelatedDataTraces(2).name= 'Yes';
% BinaryGain
Rev(2).BinaryGain(1).value=1;
Rev(2).BinaryGain(1).name='Yes';
Rev(2).BinaryGain(2).value=2;
Rev(2).BinaryGain(2).name= 'No';
% AmplitudeRecoveryMethod
Rev(2).AmplitudeRecoveryMethod(1).value=1;
Rev(2).AmplitudeRecoveryMethod(1).name='none';
Rev(2).AmplitudeRecoveryMethod(2).value=2;
Rev(2).AmplitudeRecoveryMethod(2).name= 'Spherical Divergence';
Rev(2).AmplitudeRecoveryMethod(3).value=3;
Rev(2).AmplitudeRecoveryMethod(3).name= 'AGC';
Rev(2).AmplitudeRecoveryMethod(4).value=4;
Rev(2).AmplitudeRecoveryMethod(4).name= 'Other';
% MeasurementSystem
Rev(2).MeasurementSystem(1).value=1;
Rev(2).MeasurementSystem(1).name='Meters';
Rev(2).MeasurementSystem(2).value=2;
Rev(2).MeasurementSystem(2).name= 'Feets';
% ImpulseSignalPolarity
Rev(2).ImpulseSignalPolarity(1).value=1;
Rev(2).ImpulseSignalPolarity(1).name='Negative number';
Rev(2).ImpulseSignalPolarity(2).value=2;
Rev(2).ImpulseSignalPolarity(2).name= 'Positive Number';
% VibratoryPolarityCode
Rev(2).VibratoryPolarityCode(1).value=1;
Rev(2).VibratoryPolarityCode(1).name='337.5 - 22.5';
Rev(2).VibratoryPolarityCode(2).value=2;
Rev(2).VibratoryPolarityCode(2).name= '22.5-67.5';
Rev(2).VibratoryPolarityCode(3).value=3;
Rev(2).VibratoryPolarityCode(3).name= '67.5-112.5';
Rev(2).VibratoryPolarityCode(4).value=4;
Rev(2).VibratoryPolarityCode(4).name= '112.5-157.5';
Rev(2).VibratoryPolarityCode(5).value=5;
Rev(2).VibratoryPolarityCode(5).name= '157.5-202.5';
Rev(2).VibratoryPolarityCode(6).value=6;
Rev(2).VibratoryPolarityCode(6).name= '202.5-247.5';
Rev(2).VibratoryPolarityCode(7).value=7;
Rev(2).VibratoryPolarityCode(7).name= '247.5-292.5';
Rev(2).VibratoryPolarityCode(8).value=8;
Rev(2).VibratoryPolarityCode(8).name= '292.5-337.5';
% FixedLengthTraceFlag
Rev(2).FixedLengthTraceFlag(1).value=0;
Rev(2).FixedLengthTraceFlag(1).name='Varying Trace Length';
Rev(2).FixedLengthTraceFlag(2).value=1;
Rev(2).FixedLengthTraceFlag(2).name= 'Fixed Trace Length';
|
github
|
Abakumov/MLIB-master
|
GUIEditSegyHeader.m
|
.m
|
MLIB-master/OTHER/SegyMAT/GUI/GUIEditSegyHeader.m
| 13,711 |
utf_8
|
c6e9a7b721d99210fff0e0767abf22eb
|
function varargout = GUIEditSegyHeader(varargin)
% GUIEditSegyHeader : GUI for editing the SGY header
%
% Call :
% SH=GUIEditSegyHeader(SH);
%
%
% Example :
% [Data,STH,SH]=ReadSegy('841_m.sgy');
% SH=GUIEditSegyHeader(SH);
%
%
% GUIEDITSEGYHEADER Application M-file for GUIEditSegyTraceHeader.fig
% FIG = GUIEDITSEGYHEADER launch GUIEditSegyTraceHeader GUI.
% GUIEDITSEGYHEADER('callback_name', ...) invoke the named callback.
% Last Modified by GUIDE v2.5 03-Mar-2003 15:33:07
if (nargin == 0)|(isstruct(varargin{1})) % LAUNCH GUI
fig = openfig(mfilename,'reuse');
% Use system color scheme for figure:
set(fig,'Color',get(0,'defaultUicontrolBackgroundColor'));
% Generate a structure of handles to pass to callbacks, and store it.
handles = guihandles(fig);
guidata(fig, handles);
if nargin>0,
data = guihandles(fig); % initialize it to contain handles
data.SegyHeader=varargin{1};
data.SegyHeaderOrig=varargin{1};
guidata(fig,data);
set(fig,'HandleVisibility','On')
GUIEditSegyHeader('actionSetHeader',fig,handles)
GUIEditSegyHeader('actionUpdateHeader',fig,handles)
set(fig,'HandleVisibility','CallBack')
end
% Wait for callbacks to run and window to be dismissed:
uiwait(fig);
if nargout > 0
data=guidata(fig);
if isstruct(data.SegyHeader)
varargout{1}=data.SegyHeader;
else
varargout{1} = fig;
end
end
close(handles.figure1);
set(handles.figure1,'Visible','off')
elseif ischar(varargin{1}) % INVOKE NAMED SUBFUNCTION OR CALLBACK
try
if (nargout)
[varargout{1:nargout}] = feval(varargin{:}); % FEVAL switchyard
else
feval(varargin{:}); % FEVAL switchyard
end
catch
disp(lasterr);
end
end
%| ABOUT CALLBACKS:
%| GUIDE automatically appends subfunction prototypes to this file, and
%| sets objects' callback properties to call them through the FEVAL
%| switchyard above. This comment describes that mechanism.
%|
%| Each callback subfunction declaration has the following form:
%| <SUBFUNCTION_NAME>(H, EVENTDATA, HANDLES, VARARGIN)
%|
%| The subfunction name is composed using the object's Tag and the
%| callback type separated by '_', eSweepFrequencyStart.g. 'slider2_Callback',
%| 'figure1_CloseRequestFcn', 'axis1_ButtondownFcn'.
%|
%| H is the callback object's handle (obtained using GCBO).
%|
%| EVENTDATA is empty, but reserved for future use.
%|
%| HANDLES is a structure containing handles of components in GUI using
%| tags as fieldnames, eSweepFrequencyStart.g. handles.figure1, handles.slider2. This
%| structure is created at GUI startup using GUIHANDLES and stored in
%| the figure's application data using GUIDATA. A copy of the structure
%| is passed to each callback. You can store additional information in
%| this structure at GUI startup, and you can change the structure
%| during callbacks. Call guidata(h, handles) after changing your
%| copy to replace the stored original so that subsequent callbacks see
%| the updates. Type "help guihandles" and "help guidata" for more
%| information.
%|
%| VARARGIN contains any extra arguments you have passed to the
%| callback. Specify the extra arguments by editing the callback
%| property in the inspector. By default, GUIDE sets the property to:
%| <MFILENAME>('<SUBFUNCTION_NAME>', gcbo, [], guidata(gcbo))
%| Add any extra arguments after the last argument, before the final
%| closing parenthesis.
% --------------------------------------------------------------------
% --------------------------------------------------------------------
function varargout = figure1_ResizeFcn(h, eventdata, handles, varargin)
% --------------------------------------------------------------------
function varargout = pbDone_Callback(h, eventdata, handles, varargin)
uiresume;
% --------------------------------------------------------------------
function varargout = pbCancel_Callback(h, eventdata, handles, varargin)
data=guidata(h);
data.SegyHeader=data.SegyHeaderOrig;
guidata(h,data);
uiresume;
clear name;
function actionSetHeader(h,handles)
data=guidata(h);
SH=data.SegyHeader;
% Revision
revision=SH.SegyFormatRevisionNumber;
r=1; % Default old revisoin
if revision>50, r=2;end
if revision==0, r=1;end
for i=1:length(SH.Rev), Revision{i}=SH.Rev(i).name;end
set(handles.popSegyFormatRevision,'String',Revision);
clear name;
% DataSampleFormat
DSF=SH.Rev(r).DataSampleFormat;
for i=1:length(DSF), name{i}=DSF(i).name;end
set(handles.popDataSampleFormat,'String',name);
clear name;
% TraceSorting
TS=SH.Rev(r).TraceSorting;
for i=1:length(TS), name{i}=TS(i).name;end
set(handles.popTraceSorting,'String',name);
clear name;
% Sweep Type
ST=SH.Rev(r).SweepType;
for i=1:length(ST), name{i}=ST(i).name;end
set(handles.popSweepType,'String',name);
clear name;
% BinaryGain
BG=SH.Rev(r).BinaryGain;
for i=1:length(BG), name{i}=BG(i).name;end
set(handles.popBinaryGain,'String',name);
clear name;
% TaperType
TT=SH.Rev(r).TaperType;
for i=1:length(TT), name{i}=TT(i).name;end
set(handles.popTaperType,'String',name);
clear name;
% CorrelatedDataTraces
CD=SH.Rev(r).CorrelatedDataTraces;
for i=1:length(CD), name{i}=CD(i).name;end
set(handles.popCorrelatedDataTraces,'String',name);
clear name;
% AmplitudeRecoveryMethod
ARM=SH.Rev(r).AmplitudeRecoveryMethod;
for i=1:length(ARM), name{i}=ARM(i).name;end
set(handles.popAmplitudeRecoveryMethod,'String',name);
clear name;
% MeasurementSystem
M=SH.Rev(r).MeasurementSystem;
for i=1:length(M), name{i}=M(i).name;end
set(handles.popMeasurementSystem,'String',name);
clear name;
% ImpulseSignalPolarity
ISR=SH.Rev(r).ImpulseSignalPolarity;
for i=1:length(ISR), name{i}=ISR(i).name;end
set(handles.popImpulseSignalPolarity,'String',name);
clear name;
% popVibratoryPolarityCode
VPC=SH.Rev(r).VibratoryPolarityCode;
for i=1:length(VPC), name{i}=VPC(i).name;end
set(handles.popVibratoryPolarityCode,'String',name);
clear name;
% popFixedLengthTraceFlag
FLT=SH.Rev(r).FixedLengthTraceFlag;
for i=1:length(FLT), name{i}=FLT(i).name;end
set(handles.popFixedLengthTraceFlag,'String',name);
% EDIT BOXES
set(handles.eJob,'String',SH.Job);
set(handles.eLine,'String',SH.Line);
set(handles.eReel,'String',SH.Reel);
set(handles.eDataTracePerEnsemble,'String',SH.DataTracePerEnsemble);
set(handles.eAuxiliaryTracePerEnsemble,'String',SH.AuxiliaryTracePerEnsemble);
set(handles.edt,'String',SH.dt);
set(handles.edtOrig,'String',SH.dtOrig);
set(handles.ens,'String',SH.ns);
set(handles.ensOrig,'String',SH.nsOrig);
set(handles.eEnsembleFold,'String',SH.EnsembleFold);
set(handles.eVerticalSumCode,'String',SH.VerticalSumCode);
set(handles.eSweepFrequencyStart,'String',SH.SweepFrequencyStart);
set(handles.eSweepFrequencyEnd,'String',SH.SweepFrequencyEnd);
set(handles.eSweepLength,'String',SH.SweepLength);
set(handles.eSweepChannel,'String',SH.SweepChannel);
set(handles.eSweepTaperlengthStart,'String',SH.SweepTaperlengthStart);
set(handles.eSweepTaperLengthEnd,'String',SH.SweepTaperLengthEnd);
%---------------------------------------------------------
function r=actionGetrevision(h);
data=guidata(h);
SH=data.SegyHeader;
% Revision
revision=SH.SegyFormatRevisionNumber;
r=1; % Default old revisoin
if revision>50, r=2;end
if revision==0, r=1;end
%---------------------------------------------------------
function actionUpdateHeader(h,handles)
data=guidata(h);
SH=data.SegyHeader;
% Revision
revision=SH.SegyFormatRevisionNumber;
r=1; % Default old revisoin
if revision>50, r=2;end
if revision==0, r=1;end
set(handles.popSegyFormatRevision,'value',r);
% DataSampleFormat
DSF=SH.Rev(r).DataSampleFormat;
if length(get(handles.popDataSampleFormat,'String'))<SH.DataSampleFormat,
SH.DataSampleFormat=1;
disp([mfilename,' : Using DataSampleFormat ',num2str(SH.DataSampleFormat)])
end
set(handles.popDataSampleFormat,'value',SH.DataSampleFormat);
% MAYBE THE NEXT LINES COULD BE USED FOR MORE HEADERS
% TraceSorting
TraceSortingSelect=1;
for i=1:length(SH.Rev(r).TraceSorting)
if SH.TraceSorting==SH.Rev(r).TraceSorting(i).value;
TraceSortingSelect=i;
SH.TraceSorting;
end
end
if TraceSortingSelect>length(get(handles.popTraceSorting,'String'));
TraceSortingSelect=1;
end
set(handles.popTraceSorting,'value',TraceSortingSelect);
SweepTypeSelect=1;
for i=1:length(SH.Rev(r).SweepType)
if SH.SweepType==SH.Rev(r).SweepType(i).value;
SweepTypeSelect=i;
SH.SweepType;
end
end
if SweepTypeSelect>length(get(handles.popSweepType,'String'));
SweepTypeSelect=1;
end
set(handles.popSweepType,'value',SweepTypeSelect);
data.SegyHeader=SH;
guidata(h,data)
% --------------------------------------------------------------------
function varargout = popSegyFormatRevision_Callback(h, eventdata, handles, varargin)
data=guidata(h);
sel=get(h,'value');
data.SegyHeader.SegyFormatRevisionNumber = data.SegyHeader.Rev(sel).SegyFormatRevisionNumber;
guidata(h,data);
actionSetHeader(h,handles)
actionUpdateHeader(h,handles)
% --------------------------------------------------------------------
function varargout = popDataSampleFormat_Callback(h, eventdata, handles, varargin)
data=guidata(h);
sel=get(h,'value');
data.SegyHeader.DataSampleFormat=get(h,'value');
guidata(h,data);
% --------------------------------------------------------------------
function varargout = popTraceSorting_Callback(h, eventdata, handles, varargin)
data=guidata(h);
TraceSortingSelect=get(h,'value');
r=actionGetrevision(h);
data.SegyHeader.TraceSorting=data.SegyHeader.Rev(r).TraceSorting(TraceSortingSelect).value;
guidata(h,data);
function popSweepType_Callback(h, eventdata, handles)
data=guidata(h);
SweepTypeSelect=get(h,'value');
r=actionGetrevision(h);
data.SegyHeader.SweepType=data.SegyHeader.Rev(r).SweepType(SweepTypeSelect).value;
guidata(h,data);
function popTaperType_Callback(h, eventdata, handles)
data=guidata(h);
TaperTypeSelect=get(h,'value');
r=actionGetrevision(h);
data.SegyHeader.TaperType=data.SegyHeader.Rev(r).TaperType(TaperTypeSelect).value;
guidata(h,data);
actionUpdateHeader(h,handles)
function popCorrelatedDataTraces_Callback(h, eventdata, handles)
data=guidata(h);
CorrelatedDataTracesSelect=get(h,'value');
r=actionGetrevision(h);
data.SegyHeader.CorrelatedDataTraces=data.SegyHeader.Rev(r).CorrelatedDataTraces(CorrelatedDataTracesSelect).value;
guidata(h,data);
function popBinaryGain_Callback(h, eventdata, handles)
data=guidata(h);
BinaryGainSelect=get(h,'value');
r=actionGetrevision(h);
data.SegyHeader.BinaryGain=data.SegyHeader.Rev(r).BinaryGain(BinaryGainSelect).value;
guidata(h,data);
function popAmplitudeRecoveryMethod_Callback(h, eventdata, handles)
data=guidata(h);
AmplitudeRecoveryMethodSelect=get(h,'value');
r=actionGetrevision(h);
data.SegyHeader.AmplitudeRecoveryMethod=data.SegyHeader.Rev(r).AmplitudeRecoveryMethod(AmplitudeRecoveryMethodSelect).value;
guidata(h,data);
function varargout = popMeasurementSystem_Callback(h, eventdata, handles, varargin)
data=guidata(h);
MSSelect=get(h,'value');
r=actionGetrevision(h);
data.SegyHeader.MeasurementSystem=data.SegyHeader.Rev(r).MeasurementSystem(MSSelect).value;
guidata(h,data);
function popImpulseSignalPolarity_Callback(h, eventdata, handles)
data=guidata(h);
ImpulseSignalPolaritySelect=get(h,'value');
r=actionGetrevision(h);
data.SegyHeader.ImpulseSignalPolarity=data.SegyHeader.Rev(r).ImpulseSignalPolarity(ImpulseSignalPolaritySelect).value;
guidata(h,data);
function popVibratoryPolarityCode_Callback(h, eventdata, handles)
data=guidata(h);
VibratoryPolarityCodeSelect=get(h,'value');
r=actionGetrevision(h);
data.SegyHeader.VibratoryPolarityCode=data.SegyHeader.Rev(r).VibratoryPolarityCode(VibratoryPolarityCodeSelect).value;
guidata(h,data);
% --- Executes on selection change in popFixedLengthTraceFlag.
function popFixedLengthTraceFlag_Callback(h, eventdata, handles)
data=guidata(h);
FixedLengthTraceFlagSelect=get(h,'value');
r=actionGetrevision(h);
data.SegyHeader.FixedLengthTraceFlag=data.SegyHeader.Rev(r).FixedLengthTraceFlag(FixedLengthTraceFlagSelect).value;
guidata(h,data);
% --- Executes on button press in pbEditTextualFileHeader.
function pbEditTextualFileHeader_Callback(h, eventdata, handles)
data=guidata(h);
data.SegyHeader=GUIEditTextualFileHeader(data.SegyHeader);
guidata(h,data);
function eJob_Callback(hObject, eventdata, handles)
function eLine_Callback(hObject, eventdata, handles)
function eReel_Callback(hObject, eventdata, handles)
function eDataTracePerEnsemble_Callback(hObject, eventdata, handles)
function eAuxiliaryTracePerEnsemble_Callback(hObject, eventdata, handles)
function edt_Callback(hObject, eventdata, handles)
function edtOrig_Callback(hObject, eventdata, handles)
% --- Executes during object creation, after setting all properties.
function ens_CreateFcn(hObject, eventdata, handles)
% --- Executes on button press in ens.
function ens_Callback(hObject, eventdata, handles)
% --- Executes on button press in ensOrig.
function ensOrig_Callback(hObject, eventdata, handles)
% --- Executes on button press in eEnsembleFold.
function eEnsembleFold_Callback(hObject, eventdata, handles)
% --- Executes on button press in eVerticalSumCode.
function eVerticalSumCode_Callback(hObject, eventdata, handles)
% --- Executes on button press in eSweepFrequencyStart.
function eSweepFrequencyStart_Callback(hObject, eventdata, handles)
function eSweepFrequencyEnd_Callback(hObject, eventdata, handles)
function eSweepLength_Callback(hObject, eventdata, handles)
function eSweepChannel_Callback(hObject, eventdata, handles)
function eSweepTaperlengthStart_Callback(hObject, eventdata, handles)
function eSweepTaperLengthEnd_Callback(hObject, eventdata, handles)
|
github
|
Abakumov/MLIB-master
|
GUIPlotXY.m
|
.m
|
MLIB-master/OTHER/SegyMAT/GUI/GUIPlotXY.m
| 4,482 |
utf_8
|
83486fe1795ccbd4e6bdb2cf2db3d78b
|
function varargout = GUIEditSegyTraceHeader(varargin)
% GUIPlotXY Application M-file for GUIEditSegyTraceHeader.fig
% FIG = GUIPLOTXY launch GUIEditSegyTraceHeader GUI.
% GUIPLOTXY('callback_name', ...) invoke the named callback.
%
% OBSOLETE ??
%
% Last Modified by GUIDE v2.0 16-Jun-2002 11:41:23
if (nargin == 0)|(isstruct(varargin{1})) % LAUNCH GUI
fig = openfig(mfilename,'reuse');
% Use system color scheme for figure:
set(fig,'Color',get(0,'defaultUicontrolBackgroundColor'));
% Generate a structure of handles to pass to callbacks, and store it.
handles = guihandles(fig);
guidata(fig, handles);
if nargin>0,
data = guihandles(fig); % initialize it to contain handles
data.H=varargin{1};
data.Hname=fieldnames(data.H(1));
data.NShowHeaders=7; % NUMBER OF HEADER VALUES TO LIST
data.ShowNTraces=10; % NUMBER OF TRACES TO LIST
data.StartTrace=1;
set(handles.popX,'String',data.Hname);
set(handles.popY,'String',data.Hname);
set(handles.popX,'Value',2);
set(handles.popY,'Value',4);
guidata(fig,data);
set(fig,'HandleVisibility','On')
GUIPlotXY('actionPlotData',fig,handles)
set(fig,'HandleVisibility','CallBack')
end
% Wait for callbacks to run and window to be dismissed:
uiwait(fig);
if nargout > 0
data=guidata(fig);
if isstruct(data.H)
varargout{1}=data.H
else
varargout{1} = fig;
end
end
close(handles.figure1);
try;set(handles.figure1,'Visible','off');end
elseif ischar(varargin{1}) % INVOKE NAMED SUBFUNCTION OR CALLBACK
try
if (nargout)
[varargout{1:nargout}] = feval(varargin{:}); % FEVAL switchyard
else
feval(varargin{:}); % FEVAL switchyard
end
catch
disp(lasterr);
end
end
%| ABOUT CALLBACKS:
%| GUIDE automatically appends subfunction prototypes to this file, and
%| sets objects' callback properties to call them through the FEVAL
%| switchyard above. This comment describes that mechanism.
%|
%| Each callback subfunction declaration has the following form:
%| <SUBFUNCTION_NAME>(H, EVENTDATA, HANDLES, VARARGIN)
%|
%| The subfunction name is composed using the object's Tag and the
%| callback type separated by '_', e.g. 'slider2_Callback',
%| 'figure1_CloseRequestFcn', 'axis1_ButtondownFcn'.
%|
%| H is the callback object's handle (obtained using GCBO).
%|
%| EVENTDATA is empty, but reserved for future use.
%|
%| HANDLES is a structure containing handles of components in GUI using
%| tags as fieldnames, e.g. handles.figure1, handles.slider2. This
%| structure is created at GUI startup using GUIHANDLES and stored in
%| the figure's application data using GUIDATA. A copy of the structure
%| is passed to each callback. You can store additional information in
%| this structure at GUI startup, and you can change the structure
%| during callbacks. Call guidata(h, handles) after changing your
%| copy to replace the stored original so that subsequent callbacks see
%| the updates. Type "help guihandles" and "help guidata" for more
%| information.
%|
%| VARARGIN contains any extra arguments you have passed to the
%| callback. Specify the extra arguments by editing the callback
%| property in the inspector. By default, GUIDE sets the property to:
%| <MFILENAME>('<SUBFUNCTION_NAME>', gcbo, [], guidata(gcbo))
%| Add any extra arguments after the last argument, before the final
%| closing parenthesis.
% --------------------------------------------------------------------
% --------------------------------------------------------------------
function varargout = popX_Callback(h, eventdata, handles, varargin)
actionPlotData(h,handles)
% --------------------------------------------------------------------
function varargout = popY_Callback(h, eventdata, handles, varargin)
actionPlotData(h,handles)
% --------------------------------------------------------------------
function varargout = figure1_ResizeFcn(h, eventdata, handles, varargin)
% --------------------------------------------------------------------
function varargout = pbDone_Callback(h, eventdata, handles, varargin)
uiresume;
function actionPlotData(h,handles)
data=guidata(h);
Xv=get(handles.popX,'value');
Yv=get(handles.popY,'value');
Xheader=data.Hname(Xv);
Yheader=data.Hname(Yv);
X=[data.H.(char(Xheader))];
Y=[data.H.(char(Yheader))];
axes(handles.axMain);
plot(X,Y,'k.');
xlabel(char(Xheader))
ylabel(char(Yheader))
zoom on
|
github
|
Abakumov/MLIB-master
|
GUIEditSegyTraceHeader.m
|
.m
|
MLIB-master/OTHER/SegyMAT/GUI/GUIEditSegyTraceHeader.m
| 12,255 |
utf_8
|
f0b3e4ff50241e679450646e2dfa4639
|
function varargout = GUIEditSegyTraceHeader(varargin)
% GUIEditSegyTraceHeader Application M-file for GUIEditSegyTraceHeader.fig
% FIG = GUIEDITSEGYTRACEHEADER launch GUIEditSegyTraceHeader GUI.
% GUIEDITSEGYTRACEHEADER('callback_name', ...) invoke the named callback.
% Last Modified by GUIDE v2.0 05-Jun-2002 09:24:38
if (nargin == 0)|(isstruct(varargin{1})) % LAUNCH GUI
fig = openfig(mfilename,'reuse');
% Use system color scheme for figure:
set(fig,'Color',get(0,'defaultUicontrolBackgroundColor'));
% Generate a structure of handles to pass to callbacks, and store it.
handles = guihandles(fig);
guidata(fig, handles);
if nargin>0,
data = guihandles(fig); % initialize it to contain handles
data.H=varargin{1};
data.Horig=varargin{1};
data.Hname=fieldnames(data.H(1));
data.NShowHeaders=7; % NUMBER OF HEADER VALUES TO LIST
data.ShowNTraces=10; % NUMBER OF TRACES TO LIST
data.StartTrace=1;
set(handles.popHV1,'String',data.Hname);
set(handles.popHV2,'String',data.Hname);
set(handles.popHV3,'String',data.Hname);
set(handles.popHV4,'String',data.Hname);
set(handles.popHV5,'String',data.Hname);
set(handles.popHV6,'String',data.Hname);
set(handles.popHV7,'String',data.Hname);
set(handles.popHV1,'Value',2);
set(handles.popHV2,'Value',4);
set(handles.popHV3,'Value',5);
set(handles.popHV4,'Value',7);
set(handles.popHV5,'Value',13);
set(handles.popHV6,'Value',23);
set(handles.popHV7,'Value',24);
guidata(fig,data);
set(fig,'HandleVisibility','On')
GUIEditSegyTraceHeader('actionCreateHandles',fig,handles)
set(fig,'HandleVisibility','CallBack')
end
% Wait for callbacks to run and window to be dismissed:
uiwait(fig);
if nargout > 0
data=guidata(fig);
if isstruct(data.H)
varargout{1}=data.H;
else
varargout{1} = fig;
end
end
try
close(handles.figure1);
set(handles.figure1,'Visible','off')
catch
SegymatVerbose(sprintf('%s: Could not close WINDOW',mfilename))
end
elseif ischar(varargin{1}) % INVOKE NAMED SUBFUNCTION OR CALLBACK
try
if (nargout)
[varargout{1:nargout}] = feval(varargin{:}); % FEVAL switchyard
else
feval(varargin{:}); % FEVAL switchyard
end
catch
disp(lasterr);
end
end
%| ABOUT CALLBACKS:
%| GUIDE automatically appends subfunction prototypes to this file, and
%| sets objects' callback properties to call them through the FEVAL
%| switchyard above. This comment describes that mechanism.
%|
%| Each callback subfunction declaration has the following form:
%| <SUBFUNCTION_NAME>(H, EVENTDATA, HANDLES, VARARGIN)
%|
%| The subfunction name is composed using the object's Tag and the
%| callback type separated by '_', e.g. 'slider2_Callback',
%| 'figure1_CloseRequestFcn', 'axis1_ButtondownFcn'.
%|
%| H is the callback object's handle (obtained using GCBO).
%|
%| EVENTDATA is empty, but reserved for future use.
%|
%| HANDLES is a structure containing handles of components in GUI using
%| tags as fieldnames, e.g. handles.figure1, handles.slider2. This
%| structure is created at GUI startup using GUIHANDLES and stored in
%| the figure's application data using GUIDATA. A copy of the structure
%| is passed to each callback. You can store additional information in
%| this structure at GUI startup, and you can change the structure
%| during callbacks. Call guidata(h, handles) after changing your
%| copy to replace the stored original so that subsequent callbacks see
%| the updates. Type "help guihandles" and "help guidata" for more
%| information.
%|
%| VARARGIN contains any extra arguments you have passed to the
%| callback. Specify the extra arguments by editing the callback
%| property in the inspector. By default, GUIDE sets the property to:
%| <MFILENAME>('<SUBFUNCTION_NAME>', gcbo, [], guidata(gcbo))
%| Add any extra arguments after the last argument, before the final
%| closing parenthesis.
% --------------------------------------------------------------------
function actionCreateHandles(h,handles)
data=guidata(h);
ShowNTraces=data.ShowNTraces;
MainPos=get(handles.fMain,'Position');
for ih=1:data.NShowHeaders
poph=findobj('tag',['popHV',num2str(ih)]);
HandlePos=get(poph,'Position');
X=HandlePos(1)+HandlePos(3);
Xdist=(MainPos(3)+MainPos(1))-(HandlePos(1)+HandlePos(3));
dx=Xdist/ShowNTraces;
ddx=.1;
% CREATE PLOT BUTTONS
Xwidth=HandlePos(1)-MainPos(1);
TagString=['PH',num2str(ih+10)];
h = uicontrol('units','normalized','Style', 'pushbutton','String','P',...
'Position', [MainPos(1)+ddx*Xwidth HandlePos(2) Xwidth-2*ddx*Xwidth HandlePos(4)],...
'Tag',TagString,...
'ToolTipstring',['Plot these header values'],...
'HorizontalAlignment','center',...
'Callback','GUIEditSegyTraceHeader(''actionPlotHeader'',gcbo,guidata(gcbo))');
% CREATE EDIT BOXES
for it=1:ShowNTraces;
Xpos=X+(it-1)*Xdist/(ShowNTraces);
TagString=['T',num2str(it+10),'H',num2str(ih+10)];
h = uicontrol('units','normalized','Style', 'edit','String','P',...
'Position', [Xpos+ddx*dx HandlePos(2) dx-2*ddx*dx HandlePos(4)],...
'Tag',TagString,...
'HorizontalAlignment','Right',...
'Callback','GUIEditSegyTraceHeader(''actionChangeValueAction'',gcbo,guidata(gcbo))');
end
end
for it=1:ShowNTraces;
Xpos=X+(it-1)*Xdist/(ShowNTraces);
HeaderValuePos=get(handles.fHeaderValue,'Position');
TagString=['T',num2str(it+10)];
h = uicontrol('units','normalized','Style', 'edit','String','',...
'Position', [Xpos+ddx*dx HeaderValuePos(2) dx-2*ddx*dx HeaderValuePos(4)],...
'Tag',TagString,...
'HorizontalAlignment','Right',...
'Callback','GUIEditSegyTraceHeader(''actionHandleAction'',gcbo,guidata(gcbo))');
end
actionUpdateHandles(h,handles)
% --------------------------------------------------------------------
function actionChangeValueAction(h,handles)
data=guidata(h);
Tag=get(h,'Tag');
trace=str2num(Tag(2:3))-10+(data.StartTrace-1);
ih=str2num(Tag(5:6))-10;
poph=findobj('tag',['popHV',num2str(ih)]);
headername=char(data.Hname(get(poph,'value')));
% ONLY USE THE TYPES IN VALUE IF IT IS A NUMBER
origvalue=getfield(data.H(trace),headername);
value=str2num(get(h,'string'));
if isempty(value), value=origvalue; end
% UPDATE THE HEADER VALUE
data.H(trace)=setfield(data.H(trace),headername,value);
guidata(h,data);
actionUpdateHandles(h,handles)
% --------------------------------------------------------------------
function actionUpdateHandles(h,handles)
data=guidata(h);
% MAKE SURE WE ARE NOT OUT OF BOUNDS
if data.StartTrace<1, data.StartTrace=1; end
if data.StartTrace>(length(data.H)-data.ShowNTraces+1), data.StartTrace=length(data.H)-data.ShowNTraces+1;end
for ih=1:data.NShowHeaders
poph=findobj('tag',['popHV',num2str(ih)]);
hname=char(data.Hname(get(poph,'value')));
for it=[1:data.ShowNTraces];
hvalue=getfield(data.H(it+data.StartTrace-1),hname);
TagString=['T',num2str(it+10),'H',num2str(ih+10)];
set(findobj('Tag',TagString),'String',hvalue);
end
end
for it=1:data.ShowNTraces;
TagString=['T',num2str(it+10)];
set(findobj('Tag',TagString),'String',it+data.StartTrace-1);
end
guidata(h,data);
% --------------------------------------------------------------------
function actionPlotHeader(h,handles,varargin)
if length(varargin)==1
headers=varargin{1};
else
Tag=get(h,'Tag');
headers=str2num(Tag(3:length(Tag)))-10;
end
data=guidata(h);
traces=[1:1:length(data.H)];
figure
set(gcf,'name','Plot of Trace Header Values')
nheaders=length(headers);
ch=0;
for ih=headers
ch=ch+1;
subplot(nheaders,1,ch);
poph=findobj('tag',['popHV',num2str(ih)]);
hname=char(data.Hname(get(poph,'value')));
% GET HEADER VALUES FROM STRUCTURE
for it=1:length(traces), hv(it)=getfield(data.H(it),hname); end
%bar(traces,hv);
area(traces,hv,min(hv(:)));
%hold on;bar(traces,hv); hold off
if ch==nheaders,
xlabel(['TraceNumber']);
else
set(gca,'XtickLabel','');
end
ylabel(hname);
grid on
zoom on
end
% --------------------------------------------------------------------
function varargout = pbPlotAll_Callback(h, eventdata, handles, varargin)
data=guidata(h);
actionPlotHeader(h,handles,[1:1:data.NShowHeaders]);
% --------------------------------------------------------------------
function varargout = popHV_Callback(h, eventdata, handles, varargin)
actionUpdateHandles(h,handles)
% --------------------------------------------------------------------
function varargout = popHV1_Callback(h, eventdata, handles, varargin)
data=guidata(h);
data.StartTrace=data.StartTrace+1;
guidata(h,data);
actionUpdateHandles(h,handles)
% --------------------------------------------------------------------
function varargout = popHV2_Callback(h, eventdata, handles, varargin)
% --------------------------------------------------------------------
function varargout = popHV3_Callback(h, eventdata, handles, varargin)
% --------------------------------------------------------------------
function varargout = popHV4_Callback(h, eventdata, handles, varargin)
% --------------------------------------------------------------------
function varargout = popHV5_Callback(h, eventdata, handles, varargin)
% --------------------------------------------------------------------
function varargout = popHV6_Callback(h, eventdata, handles, varargin)
% --------------------------------------------------------------------
function varargout = popHV7_Callback(h, eventdata, handles, varargin)
% --------------------------------------------------------------------
% -------------- JUMP IN THE TRACES ----------------------------------
% --------------------------------------------------------------------
%
% --------------------------------------------------------------------
function varargout = pbLeftStart_Callback(h, eventdata, handles, varargin)
data=guidata(h);
data.StartTrace=1;
guidata(h,data);
actionUpdateHandles(h,handles)
% --------------------------------------------------------------------
function varargout = pbLeftJump_Callback(h, eventdata, handles, varargin)
data=guidata(h);
data.StartTrace=data.StartTrace-data.ShowNTraces;
guidata(h,data);
actionUpdateHandles(h,handles)
% --------------------------------------------------------------------
function varargout = pbLeft_Callback(h, eventdata, handles, varargin)
data=guidata(h);
data.StartTrace=data.StartTrace-1;
guidata(h,data);
actionUpdateHandles(h,handles)
% --------------------------------------------------------------------
function varargout = pbRight_Callback(h, eventdata, handles, varargin)
data=guidata(h);
data.StartTrace=data.StartTrace+1;
guidata(h,data);
actionUpdateHandles(h,handles)
% --------------------------------------------------------------------
function varargout = pbRightJump_Callback(h, eventdata, handles, varargin)
data=guidata(h);
data.StartTrace=data.StartTrace+data.ShowNTraces;
StartTrace=data.StartTrace;
guidata(h,data);
actionUpdateHandles(h,handles)
% --------------------------------------------------------------------
function varargout = pbRightEnd_Callback(h, eventdata, handles, varargin)
data=guidata(h);
data.StartTrace=length(data.H)-data.ShowNTraces+1;
guidata(h,data);
actionUpdateHandles(h,handles)
% --------------------------------------------------------------------
function varargout = figure1_ResizeFcn(h, eventdata, handles, varargin)
% --------------------------------------------------------------------
function varargout = pbDone_Callback(h, eventdata, handles, varargin)
uiresume;
% --------------------------------------------------------------------
function varargout = pbClose_Callback(h, eventdata, handles, varargin)
data=guidata(h);
data.H=data.Horig;
guidata(h,data);
uiresume;
% --------------------------------------------------------------------
function varargout = pbReset_Callback(h, eventdata, handles, varargin)
data=guidata(h);
data.H=data.Horig;
guidata(h,data);
actionUpdateHandles(h,handles)
|
github
|
Abakumov/MLIB-master
|
DIAOpenSEGY.m
|
.m
|
MLIB-master/OTHER/SegyMAT/GUI/DIAOpenSEGY.m
| 10,847 |
utf_8
|
c3f2f42817950cc5a4526966e9a51dd0
|
function varargout = DIAOpenSEGY(varargin)
% DIAOPENSEGY Application M-file for DIAOpenSEGY.fig
% FIG = DIAOPENSEGY launch DIAOpenSEGY GUI.
% DIAOPENSEGY('callback_name', ...) invoke the named callback.
% Last Modified by GUIDE v2.0 12-Jun-2002 10:25:58
if ((nargin == 0)|isstruct(varargin{1})) % LAUNCH GUI
fig = openfig(mfilename,'reuse');
% Use system color scheme for figure:
set(fig,'Color',get(0,'defaultUicontrolBackgroundColor'));
% Generate a structure of handles to pass to callbacks, and store it.
handles = guihandles(fig);
guidata(fig, handles);
data = guihandles(fig); % initialize it to contain handles
data.JUMP.jump=5;
data.JUMP.enable=0;
data.TRACEHEADER.name='offset';
data.TRACEHEADER.min=1;
data.TRACEHEADER.max=1e+9;
data.TRACEHEADER.enable=0;
data.TIMERANGE.min=1;
data.TIMERANGE.max=5;
data.TIMERANGE.enable=0;
if nargin==0;
data.pathname='';
data.filename='';
guidata(fig,data);
else
try;data.JUMP=varargin{1}.JUMP;end
try;data.TRACEHEADER=varargin{1}.TRACEHEADER;end
try;data.TIMERANGE=varargin{1}.TIMERANGE;end
if isfield(varargin{1},'pathname');data.pathname=varargin{1}.pathname;end;
if isfield(varargin{1},'filename');data.filename=varargin{1}.filename;end
end
guidata(fig,data);
set(fig,'HandleVisibility','On')
DIAOpenSEGY('actionUpdateGUI',fig,handles)
set(fig,'HandleVisibility','CallBack')
% Wait for callbacks to run and window to be dismissed:
uiwait(fig);
if nargout > 0
data=guidata(fig);
SEGYFILE.JUMP=data.JUMP;
SEGYFILE.TRACEHEADER=data.TRACEHEADER;
SEGYFILE.TIMERANGE=data.TIMERANGE;
if isfield(data,'SegyHeader')
SEGYFILE.SegyHeader=data.SegyHeader;
end
if isfield(data,'filename'),SEGYFILE.filename=data.filename;end
if isfield(data,'pathname'),SEGYFILE.pathname=data.pathname;end
varargout{1} = SEGYFILE;
end
close(handles.figure1);
try;set(handles.figure1,'Visible','off');end
elseif ischar(varargin{1}) % INVOKE NAMED SUBFUNCTION OR CALLBACK
try
if (nargout)
[varargout{1:nargout}] = feval(varargin{:}); % FEVAL switchyard
else
feval(varargin{:}); % FEVAL switchyard
end
catch
disp(lasterr);
end
end
%| ABOUT CALLBACKS:
%| GUIDE automatically appends subfunction prototypes to this file, and
%| sets objects' callback properties to call them through the FEVAL
%| switchyard above. This comment describes that mechanism.
%|
%| Each callback subfunction declaration has the following form:
%| <SUBFUNCTION_NAME>(H, EVENTDATA, HANDLES, VARARGIN)
%|
%| The subfunction name is composed using the object's Tag and the
%| callback type separated by '_', e.g. 'slider2_Callback',
%| 'figure1_CloseRequestFcn', 'axis1_ButtondownFcn'.
%|
%| H is the callback object's handle (obtained using GCBO).
%|
%| EVENTDATA is empty, but reserved for future use.
%|
%| HANDLES is a structure containing handles of components in GUI using
%| tags as fieldnames, e.g. handles.figure1, handles.slider2. This
%| structure is created at GUI startup using GUIHANDLES and stored in
%| the figure's application data using GUIDATA. A copy of the structure
%| is passed to each callback. You can store additional information in
%| this structure at GUI startup, and you can change the structure
%| during callbacks. Call guidata(h, handles) after changing your
%| copy to replace the stored original so that subsequent callbacks see
%| the updates. Type "help guihandles" and "help guidata" for more
%| information.
%|
%| VARARGIN contains any extra arguments you have passed to the
%| callback. Specify the extra arguments by editing the callback
%| property in the inspector. By default, GUIDE sets the property to:
%| <MFILENAME>('<SUBFUNCTION_NAME>', gcbo, [], guidata(gcbo))
%| Add any extra arguments after the last argument, before the final
%| closing parenthesis.
function actionUpdateGUI(h,handles)
data=guidata(h);
% RESET FILEMAME,PATHNAME if FILE DOES NOT EXIST
if isfield(data,'filename')
if exist([data.pathname,data.filename])~=2
data=rmfield(data,'filename');
data=rmfield(data,'pathname');
end
end
% CHECK THAT A FILENAME I SET, and disbale if not.
if isfield(data,'filename'),
cbEnable='on';
set(handles.eFilename,'String',[data.pathname,data.filename]);
else
cbEnable='off';
set(handles.eFilename,'String','');
end
set(findobj('style','checkbox'),'enable',cbEnable)
% JUMP
set(handles.cbJump,'Value',data.JUMP.enable);
data.Jump.value=get(handles.cbJump,'Value');
if ((get(handles.cbJump,'Value')==1)&(isfield(data,'filename'))),
enableJump='on';
data.JUMP.enable=1;
else,
enableJump='off';
data.JUMP.enable=0;
end
set(handles.eJump,'Enable',enableJump)
set(handles.eJump,'String',data.JUMP.jump)
% TraceHeader
set(handles.cbTraceHeader,'Value',data.TRACEHEADER.enable);
data.TraceHeader.value=get(handles.cbTraceHeader,'Value');
if ((get(handles.cbTraceHeader,'Value')==1)&(isfield(data,'filename'))),
enableTraceHeader='on';
data.TRACEHEADER.enable=1;
else,
enableTraceHeader='off';
data.TRACEHEADER.enable=0;
end
hnames=get(handles.popTraceHeader,'string');
selected=get(handles.popTraceHeader,'value');
for i=1:length(hnames)
if strcmp(hnames{i},data.TRACEHEADER.name),
set(handles.popTraceHeader,'Value',i);
end
end
set(handles.popTraceHeader,'Enable',enableTraceHeader)
set(handles.eTraceHeaderMin,'Enable',enableTraceHeader)
set(handles.eTraceHeaderMin,'String',data.TRACEHEADER.min)
set(handles.eTraceHeaderMax,'Enable',enableTraceHeader)
set(handles.eTraceHeaderMax,'String',data.TRACEHEADER.max)
% TimeRange
set(handles.cbTimeRange,'Value',data.TIMERANGE.enable);
data.TimeRange.value=get(handles.cbTimeRange,'Value');
if ((get(handles.cbTimeRange,'Value')==1)&(isfield(data,'filename'))),
enableTimeRange='on';
data.TIMERANGE.enable=1;
else,
data.TIMERANGE.enable=0;
enableTimeRange='off';
end
set(handles.eTimeRangeMin,'Enable',enableTimeRange)
set(handles.eTimeRangeMin,'String',data.TIMERANGE.min)
set(handles.eTimeRangeMax,'Enable',enableTimeRange)
set(handles.eTimeRangeMax,'String',data.TIMERANGE.max)
guidata(h,data)
% --------------------------------------------------------------------
function varargout = eFilename_Callback(h, eventdata, handles, varargin)
% --------------------------------------------------------------------
function varargout = pbSelectFile_Callback(h, eventdata, handles, varargin)
data=guidata(h);
[filename, pathname] = uigetfile('*.su;*.SU;*.sgy;*.SGY;*.seg*;*.SEGY', 'Pick a SEGY or SU file');
if isequal(filename,0)|isequal(pathname,0)
disp('File not found')
return
else
disp(['File ', pathname, filename, ' found'])
set(handles.eFilename,'String',[pathname,filename])
data.pathname=pathname;
data.filename=filename;
end
guidata(h,data)
actionUpdateGUI(h,handles)
% --------------------------------------------------------------------
function varargout = cbJump_Callback(h, eventdata, handles, varargin)
data=guidata(h);
data.JUMP.enable=get(h,'Value');
guidata(h,data);
actionUpdateGUI(h,handles)
% --------------------------------------------------------------------
function varargout = eJump_Callback(h, eventdata, handles, varargin)
data=guidata(h);
if ~isempty(str2num(get(h,'String')));data.JUMP.jump=str2num(get(h,'String'));end
guidata(h,data);
actionUpdateGUI(h,handles)
% --------------------------------------------------------------------
function varargout = cbTraceHeader_Callback(h, eventdata, handles, varargin)
data=guidata(h);
data.TRACEHEADER.enable=get(h,'Value');
guidata(h,data);
actionUpdateGUI(h,handles)
% --------------------------------------------------------------------
function varargout = popTraceHeader_Callback(h, eventdata, handles, varargin)
data=guidata(h);
hnames=get(h,'string');
selected=get(h,'value');
data.TRACEHEADER.name=hnames{selected};
guidata(h,data);
actionUpdateGUI(h,handles)
% --------------------------------------------------------------------
function varargout = eTraceHeaderMin_Callback(h, eventdata, handles, varargin)
data=guidata(h);
if ~isempty(str2num(get(h,'String')));data.TRACEHEADER.min=str2num(get(h,'String'));end
if data.TRACEHEADER.min>data.TRACEHEADER.max
data.TRACEHEADER.min=data.TRACEHEADER.max;
end
guidata(h,data);
actionUpdateGUI(h,handles)
% --------------------------------------------------------------------
function varargout = eTraceHeaderMax_Callback(h, eventdata, handles, varargin)
data=guidata(h);
if ~isempty(str2num(get(h,'String')));data.TRACEHEADER.max=str2num(get(h,'String'));end
if data.TRACEHEADER.max<data.TRACEHEADER.min
data.TRACEHEADER.max=data.TRACEHEADER.min;
end
guidata(h,data);
actionUpdateGUI(h,handles)
% --------------------------------------------------------------------
function varargout = cbTimeRange_Callback(h, eventdata, handles, varargin)
data=guidata(h);
data.TIMERANGE.enable=get(h,'Value');
guidata(h,data);
actionUpdateGUI(h,handles)
% --------------------------------------------------------------------
function varargout = eTimeRangeMin_Callback(h, eventdata, handles, varargin)
data=guidata(h);
if ~isempty(str2num(get(h,'String')));data.TIMERANGE.min=str2num(get(h,'String'));end
if data.TIMERANGE.min>data.TIMERANGE.max;
data.TIMERANGE.min=data.TIMERANGE.max;
end
guidata(h,data);
actionUpdateGUI(h,handles)
% --------------------------------------------------------------------
function varargout = eTimeRangeMax_Callback(h, eventdata, handles, varargin)
data=guidata(h);
if ~isempty(str2num(get(h,'String')));data.TIMERANGE.max=str2num(get(h,'String'));end
if data.TIMERANGE.max<data.TIMERANGE.min
data.TIMERANGE.max=data.TIMERANGE.min;
end
guidata(h,data);
actionUpdateGUI(h,handles)
% --------------------------------------------------------------------
function varargout = pbReadSegy_Callback(h, eventdata, handles, varargin)
uiresume
% --------------------------------------------------------------------
function varargout = pbCancel_Callback(h, eventdata, handles, varargin)
data=guidata(h);
if isfield(data,'filename'), data=rmfield(data,'filename'); end
if isfield(data,'pathname'), data=rmfield(data,'pathname'); end
guidata(h,data);
uiresume
% --------------------------------------------------------------------
function varargout = pbGUIEditSegyHeader_Callback(h, eventdata, handles, varargin)
data=guidata(h);
% GET SEGY HEDER FROM FILE, UNLESS WE ALLREADY GOT IT
if isfield(data,'SegyHeader')==0
data.SegyHeader=GetSegyHeader([data.pathname,data.filename]);
end
% EDIT THE SEGY HEADER
data.SegyHeader=GUIEditSegyHeader(data.SegyHeader);
guidata(h,data);
|
github
|
Abakumov/MLIB-master
|
GUIEditTextualFileHeader.m
|
.m
|
MLIB-master/OTHER/SegyMAT/GUI/GUIEditTextualFileHeader.m
| 9,895 |
utf_8
|
8519ae23ae7d6817ea863c7c0fd7c059
|
function varargout = GUIEditTextualFileHeader(varargin)
% GUIEditTextualFileHeader : GUI for editing the SGY header
%
% Call :
% SH=GUIEditTextualFileHeader(SH);
%
%
% Example :
% [Data,STH,SH]=ReadSegy('841_m.sgy');
% SH=GUIEditTextualFileHeader(SH);
%
%
% GUIEDITTEXTUALFILEHEADER M-file for GUIEditTextualFileHeader.fig
% GUIEDITTEXTUALFILEHEADER, by itself, creates a new GUIEDITTEXTUALFILEHEADER or raises the existing
% singleton*.
%
% H = GUIEDITTEXTUALFILEHEADER returns the handle to a new GUIEDITTEXTUALFILEHEADER or the handle to
% the existing singleton*.
%
% GUIEDITTEXTUALFILEHEADER('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in GUIEDITTEXTUALFILEHEADER.M with the given input arguments.
%
% GUIEDITTEXTUALFILEHEADER('Property','Value',...) creates a new GUIEDITTEXTUALFILEHEADER or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before GUIEditTextualFileHeader_OpeningFunction gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to GUIEditTextualFileHeader_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 GUIEditTextualFileHeader
% Last Modified by GUIDE v2.5 05-Jan-2009 17:27:47
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @GUIEditTextualFileHeader_OpeningFcn, ...
'gui_OutputFcn', @GUIEditTextualFileHeader_OutputFcn, ...
'gui_LayoutFcn', [] , ...
'gui_Callback', []);
if nargin & isstr(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 GUIEditTextualFileHeader is made visible.
function GUIEditTextualFileHeader_OpeningFcn(hObject, eventdata, handles, varargin)
% 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 GUIEditTextualFileHeader (see VARARGIN)
% Choose default command line output for GUIEditTextualFileHeader
handles.output = hObject;
% Update handles structure
guidata(hObject, handles);
% Load TextualFileHeader if given
if length(varargin)>0
if nargin & isstruct(varargin{1})
if isfield(varargin{1},'TextualFileHeader')
data=guidata(gcf);
data.SegyHeader=varargin{1};
data.SegyHeaderOrg=data.SegyHeader;
if isempty(find(data.SegyHeader.TextualFileHeader>200))
HeaderType=2; % ASCII
else
HeaderType=1; % EBCDIC
end
set(handles.popType,'Value',HeaderType);
guidata(gcf, data);
UpdateText(hObject, handles)
end
end
end
% UIWAIT makes GUIEditTextualFileHeader wait for user response (see UIRESUME)
uiwait(handles.figTextualHeader);
% --- Outputs from this function are returned to the command line.
function varargout = GUIEditTextualFileHeader_OutputFcn(hObject, eventdata, handles)
% 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
data=guidata(gcf);
varargout{1} = data.SegyHeader;
close(handles.figTextualHeader);
% --- Executes during object creation, after setting all properties.
function eTextHeader_CreateFcn(hObject, eventdata, handles)
% hObject handle to eTextHeader (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc
set(hObject,'BackgroundColor','white');
else
set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end
function eTextHeader_Callback(hObject, eventdata, handles)
% hObject handle to eTextHeader (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of eTextHeader as text
% str2double(get(hObject,'String')) returns contents of
% eTextHeader as a double
%eTextHeader_Callback(handles.eTextHeader, eventdata, handles)
HS=get(hObject,'String');
VAL=get(hObject,'Value');
data=guidata(hObject);
data.HS=HS;
data.VAL=VAL;
%disp(sprintf('LINE=''%s''',HS(VAL,:)))
guidata(hObject, data);
% UPDATE TEXT STRING
set(handles.eEditLine,'String',HS(VAL,:))
% --- Executes during object creation, after setting all properties.
function popType_CreateFcn(hObject, eventdata, handles)
% hObject handle to popType (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: popupmenu controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc
set(hObject,'BackgroundColor','white');
else
set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end
% --- Executes on selection change in popType.
function popType_Callback(hObject, eventdata, handles)
% hObject handle to popType (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: contents = get(hObject,'String') returns popType contents as cell array
% contents{get(hObject,'Value')} returns selected item from
% popType
UpdateText(hObject,handles)
function UpdateText(hObject, handles)
data=guidata(hObject);
HeaderType=get(handles.popType,'Value');
if HeaderType==1,
txt=char(ebcdic2ascii(data.SegyHeader.TextualFileHeader));
else
txt=char(data.SegyHeader.TextualFileHeader');
end
%disp('--')
%reshape(txt,80,40)'
%disp('--')
%disp(size(txt))
try
s=[];
for i=1:40;
s=[s,txt((i-1)*80+1:(i-1)*80+80)];
try
if i~=40, s=[s,'|']; end
catch
keyboard
end
end
catch
if (HeaderType==1)
warndlg(['The Textual Header is most probably NOT EBCDIC formatted'],'Textual Header Info')
else
warndlg(['The Textual Header is most probably NOT ASCII formatted'],'Textual Header Info')
end
end
try
set(handles.eTextHeader,'String',s)
catch
disp('WHUUPS')
end
% --- Executes during object creation, after setting all properties.
function eEditLine_CreateFcn(hObject, eventdata, handles)
% hObject handle to eEditLine (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc
set(hObject,'BackgroundColor','white');
else
set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end
function eEditLine_Callback(hObject, eventdata, handles)
% hObject handle to eEditLine (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of eEditLine as text
% str2double(get(hObject,'String')) returns contents of eEditLine as a double
data=guidata(hObject);
if ~isfield(data,'HS')
eTextHeader_Callback(handles.eTextHeader, eventdata, handles)
data=guidata(hObject);
end
try
NEWSTR=get(hObject,'String');
n=length(NEWSTR);
if n<80
NEWSTR(n+1:80)=' ';
end
n=length(NEWSTR);
if n>=80
data.HS(data.VAL,:)=NEWSTR(1:80);
else
data.HS(data.VAL,1:n)=NEWSTR(1:n);
end
HStransp=data.HS';
if get(handles.popType,'Value')==1;
% EBCDIC
data.SegyHeader.TextualFileHeader=double(ascii2ebcdic(HStransp(:)));
else
% ASCII
data.SegyHeader.TextualFileHeader=double(HStransp(:));
end
guidata(gcf, data);
UpdateText(hObject, handles)
eTextHeader_Callback(handles.eTextHeader, eventdata, handles)
catch
keyboard
end
% --- Executes on button press in pbClose.
function pbClose_Callback(hObject, eventdata, handles)
% hObject handle to pbClose (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
uiresume;
% --- Executes on button press in pbReset.
function pbReset_Callback(hObject, eventdata, handles)
% hObject handle to pbReset (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
data=guidata(gcf);
data.SegyHeader=data.SegyHeaderOrg;
guidata(gcf, data);
UpdateText(hObject, handles)
% --- Executes on button press in pbFont.
function pbFont_Callback(hObject, eventdata, handles)
% hObject handle to pbFont (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
d = uisetfont(handles.eTextHeader);
% Apply those settings to c2
set(handles.eEditLine,d);
|
github
|
Abakumov/MLIB-master
|
segymat.m
|
.m
|
MLIB-master/OTHER/SegyMAT/GUI/segymat.m
| 33,348 |
utf_8
|
b863356b762b97f58d443cb5a7664805
|
function varargout = segymat(varargin)
% segymat : Garphical User Interface for SegyMAT
%
% (C) 2001-2004 Thomas Mejer Hansen, [email protected]/[email protected]
%
% SEGYMAT M-file for segymat.fig
% SEGYMAT, by itself, creates a new SEGYMAT or raises the existing
% singleton*.
%
% H = SEGYMAT returns the handle to a new SEGYMAT or the handle to
% the existing singleton*.
%
% SEGYMAT('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in SEGYMAT.M with the given input arguments.
%
% SEGYMAT('Property','Value',...) creates a new SEGYMAT or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before segymat_OpeningFunction gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to segymat_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 segymat
% Last Modified by GUIDE v2.5 05-Jan-2009 17:29:20
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @segymat_OpeningFcn, ...
'gui_OutputFcn', @segymat_OutputFcn, ...
'gui_LayoutFcn', [] , ...
'gui_Callback', []);
% Next line is edited
% ORIGINAL : if nargin & isstr(varargin{1})
if nargin>1 & isstr(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
if nargin==1 & isstr(varargin{1})
[path,file,suffix]=fileparts(varargin{1});
segyfile.pathname=path;
if length(suffix)>1,
segyfile.filename=[file,'.',suffix];
else
segyfile.filename=file;
end
% FIGURE OUT HOW TO GET THE hObject ??
% fReadSegy_Callback(hObject, eventdata, handles,segyfile);
end
% End initialization code - DO NOT EDIT
% --- Executes just before segymat is made visible.
function segymat_OpeningFcn(hObject, eventdata, handles, varargin)
% 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 segymat (see VARARGIN)
SegymatVerbose(['GUI : OPENING GUI'],20)
% Choose default command line output for segymat
handles.output = hObject;
% Initialize PlotPref
handles.PlotPref.Show=0;
% Update handles structure
guidata(hObject, handles);
% Resize Figure
fMain_ResizeFcn(hObject, eventdata, handles)
% read in segy file
segyfile.pathname='c:\MaTLAB6p5\work\';
segyfile.filename='test.sgy';
%segyfile.filename='peaksh.segy';
%fReadSegy_Callback(hObject, eventdata, handles,segyfile);
% disable edit menu
UpdateMenus(hObject, eventdata, handles)
% UIWAIT makes segymat wait for user response (see UIRESUME)
% uiwait(handles.fMain);
% --- Outputs from this function are returned to the command line.
function varargout = segymat_OutputFcn(hObject, eventdata, handles)
% 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.output;
% --- Executes when fMain window is resized.
function fMain_ResizeFcn(hObject, eventdata, handles)
% hObject handle to fMain (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
if (isfield(handles,'fMain')==0)
return
end
SegymatVerbose(['GUI : Resizing'],20)
data=guidata(hObject);
% Get Size of Main Window
[mainPos]=get(handles.fMain,'Position');
d=4; % Distance to edges
d_ax=.2; % distance between axes
if isfield(data,'PlotPref')==0,
data.PlotPref.Show=1;
guidata(hObject,data);
end
if isfield(data.PlotPref,'Show')==0,
data.PlotPref.Show=1;
guidata(hObject,data);
end
% fHeader Location
if data.PlotPref.Show==0,
fHeaderW=d;
set(handles.fHeader,'Visible','Off');
set(handles.text7,'Visible','Off');
set(handles.txtGain,'Visible','Off');
set(handles.pbGainUp,'Visible','Off');
set(handles.pbGainDown,'Visible','Off');
set(handles.eGainMin,'Visible','Off');
set(handles.eGainMax,'Visible','Off');
set(handles.popTop,'Visible','Off');
set(handles.popBot,'Visible','Off');
set(handles.txtTop,'Visible','Off');
set(handles.txtBot,'Visible','Off');
set(handles.txtColormap,'Visible','Off');
set(handles.popColormap,'Visible','Off');
set(handles.txtStyle,'Visible','Off');
set(handles.popStyle,'Visible','Off');
else
fHeaderW=30; % WIDTH OF INFO PAGE
x0=d;y0=d;
w=fHeaderW-d;
h=mainPos(4)-2*d;
x1=x0+w;
y1=y0+h;
Wuic=8; % WIDTH OF UICONTROL
Huic=1.4; % HEIGHT OF UICONTROL
set(handles.fHeader,'Position',[x0 y0 w h])
d_frame=1;
x0=x0+d_frame;
wframe=w-2*d_frame;
% TXT HEADER
ytop=mainPos(4)-d;
% set(handles.text7,'Position',[d+d ytop fHeaderW-3*d 2]);
set(handles.text7,'Position',[x0 ytop wframe 2]);
% GAIN
ytop=ytop-d_ax-Huic;
set(handles.txtGain,'Position',[x0,ytop,wframe,Huic])
ytop=ytop-d_ax-Huic;
w_sign=4;
set(handles.eGainMin,'Position',[x0,ytop,wframe-w_sign,Huic])
set(handles.pbGainDown,'Position',[x0+wframe-w_sign,ytop,w_sign,Huic])
ytop=ytop-d_ax-Huic;
set(handles.eGainMax,'Position',[x0,ytop,Wuic*1.5,Huic])
set(handles.pbGainUp,'Position',[x0+Wuic*1.5,ytop,Wuic/2,Huic])
set(handles.eGainMax,'Position',[x0,ytop,wframe-w_sign,Huic])
set(handles.pbGainUp,'Position',[x0+wframe-w_sign,ytop,w_sign,Huic])
% TopSub
ytop=ytop-2*d_ax-Huic;
set(handles.txtTop,'Position',[x0,ytop,wframe,Huic])
ytop=ytop-d_ax-Huic;
set(handles.popTop,'Position',[x0,ytop,wframe,Huic])
% BaseSub
ytop=ytop-2*d_ax-Huic;
set(handles.txtBot,'Position',[x0,ytop,wframe,Huic])
ytop=ytop-d_ax-Huic;
set(handles.popBot,'Position',[x0,ytop,wframe,Huic])
% Style
ytop=ytop-2*d_ax-Huic;
set(handles.txtStyle,'Position',[x0,ytop,wframe,Huic])
ytop=ytop-d_ax-Huic;
set(handles.popStyle ,'Position',[x0,ytop,wframe,Huic])
% Colormap
ytop=ytop-2*d_ax-Huic;
set(handles.txtColormap,'Position',[x0,ytop,wframe,Huic])
ytop=ytop-d_ax-Huic;
set(handles.popColormap ,'Position',[x0,ytop,wframe,Huic])
%
% MAKE ALL VISIBLE
set(handles.fHeader,'Visible','On');
set(handles.text7,'Visible','On');
set(handles.txtGain,'Visible','On');
set(handles.pbGainUp,'Visible','On');
set(handles.pbGainDown,'Visible','On');
set(handles.eGainMin,'Visible','On');
set(handles.eGainMax,'Visible','On');
set(handles.popTop,'Visible','On');
set(handles.popBot,'Visible','On');
set(handles.txtTop,'Visible','On');
set(handles.txtBot,'Visible','On');
set(handles.txtColormap,'Visible','On');
set(handles.popColormap,'Visible','On');
set(handles.txtStyle,'Visible','On');
set(handles.popStyle,'Visible','On');
end
% AXIS
axLeft=fHeaderW+2*d;
Hsmallax=4;
% axBot
axBotX=axLeft;
axBotY=d;
axBotW=mainPos(3)-axLeft-2*d;
axBotH=Hsmallax;
axB=get(handles.axBot,'Position');
set(handles.axBot,'Position',[axBotX axBotY axBotW axBotH])
% axTop
axTopX=axLeft;
axTopY=mainPos(4)-Hsmallax-d;
axTopW=axBotW;
axTopH=Hsmallax;
axT=get(handles.axTop,'Position');
set(handles.axTop,'Position',[axTopX axTopY axTopW axTopH])
% axMain
axMainX=axLeft;
axMainY=axBotY+Hsmallax+d_ax;
axMainW=axBotW;
axMainH=mainPos(4)-axMainY-Hsmallax-d-d_ax;
set(handles.axMain,'Position',[axMainX axMainY axMainW axMainH])
% --------------------------------------------------------------------
function UpdatePrefs(hObject, eventdata, handles)
SegymatVerbose(['GUI : UpdatePrefs'],20)
data=guidata(hObject);
if isfield(data,'SegyData')==0,
set(handles.eGainMin,'Enable','off');
set(handles.eGainMin,'String','');
set(handles.eGainMax,'Enable','off');
set(handles.eGainMax,'String','');
return
else
set(handles.eGainMin,'Enable','on');
set(handles.eGainMax,'Enable','on');
end
if isfield(data.PlotPref,'caxis')==0
data.PlotPref.caxis=[min(data.SegyData(:)) max(data.SegyData(:))];
end
set(handles.eGainMin,'String',data.PlotPref.caxis(1));
set(handles.eGainMax,'String',data.PlotPref.caxis(2));
if isfield(data.PlotPref,'TraceHeaders')==0,
data.PlotPref.TraceHeaders=fieldnames(data.SegyTraceHeaders);
end
if isfield(data.PlotPref,'TopPlot')==0, data.PlotPref.TopPlot=7; end
if isfield(data.PlotPref,'BotPlot')==0, data.PlotPref.BotPlot=13; end
set(handles.popTop,'String',data.PlotPref.TraceHeaders);
set(handles.popTop,'value',data.PlotPref.TopPlot);
set(handles.popTop,'Enable','On');
set(handles.popBot,'String',data.PlotPref.TraceHeaders);
set(handles.popBot,'value',data.PlotPref.BotPlot);
set(handles.popBot,'Enable','On');
guidata(hObject,data);
% --------------------------------------------------------------------
function UpdatePlots(hObject, eventdata, handles)
SegymatVerbose(['GUI : Update Plots'],20)
%data=guidata(hObject);
UpdateMainPlot(hObject, eventdata, handles)
UpdateTopPlot(hObject, eventdata, handles)
UpdateBotPlot(hObject, eventdata, handles)
axes(handles.axMain);%%%zoom on;
% --------------------------------------------------------------------
function UpdateMainPlot(hObject, eventdata, handles)
SegymatVerbose(['GUI : Update Main Plot'],20)
data=guidata(hObject);
Style=get(handles.popStyle,'Value'); % GET PLOTTING STYLE
axes(handles.axMain);
if ((Style==1)|(Style==4)|(Style==5))
imagesc(data.SegyTrace,data.SegyTime,data.SegyData);
caxis(data.PlotPref.caxis)
hold on
end
gain=max(abs(data.PlotPref.caxis));
if ((Style==2)|(Style==4))
wiggle(data.SegyTrace,data.SegyTime,data.SegyData,'wiggle',gain);
end
if ((Style==3)|(Style==5))
wiggle(data.SegyTrace,data.SegyTime,data.SegyData,'VA',gain);
end
hold off
set(gca,'YaxisLocation','Right');
set(gca,'XtickLabel',[]);
ylabel('TWT [ms]')
%% RESET ZOOM SUCH THAT THIS STATE IS THE 'ZOOM OUT' STATE.
zoom reset;
%%%zoom on;
% --------------------------------------------------------------------
function UpdateTopPlot(hObject, eventdata, handles)
SegymatVerbose(['GUI : Update TOP Plots'],60)
data=guidata(hObject);
axes(handles.axMain);axMain=axis;
pop=get(handles.popTop,'String');
ipop=get(handles.popTop,'value');
hname=pop{ipop};
axes(handles.axTop)
if isfield(data,'dTopPlot')
if ipop~=data.dTopPlot_ipop
data.dTopPlot=bar([data.SegyTraceHeaders.(hname)]);
data.dTopPlot_ipop=ipop;
guidata(hObject,data)
end
else
data.dTopPlot=bar([data.SegyTraceHeaders.(hname)]);
data.dTopPlot_ipop=ipop;
guidata(hObject,data)
end
ax=axis;axis([axMain(1) axMain(2) ax(3) ax(4)])
set(gca,'XaxisLocation','Top');
set(gca,'YaxisLocation','Right');
xlabel(hname)
axes(handles.axMain);%%%zoom on;
function UpdateBotPlot(hObject, eventdata, handles)
SegymatVerbose(['GUI : Update BOT Plots'],60)
data=guidata(hObject);
axes(handles.axMain);axMain=axis;
pop=get(handles.popBot,'String');
ipop=get(handles.popBot,'value');
hname=pop{ipop};
axes(handles.axBot)
if isfield(data,'dBotPlot')
if ipop~=data.dBotPlot_ipop
data.dBotPlot=plot([data.SegyTraceHeaders.(hname)]);
data.dBotPlot_ipop=ipop;
guidata(hObject,data)
end
else
data.dBotPlot=plot([data.SegyTraceHeaders.(hname)]);
data.dBotPlot_ipop=ipop;
guidata(hObject,data)
end
% bar([data.SegyTraceHeaders.(hname)]);
ax=axis;axis([axMain(1) axMain(2) ax(3) ax(4)])
set(gca,'XaxisLocation','Bot');
set(gca,'YaxisLocation','Right');
xlabel(hname)
axes(handles.axMain);%%%zoom on;
% --------------------------------------------------------------------
function UpdateGain(hObject, eventdata, handles)
SegymatVerbose(['GUI : UpdateGain'],20)
data=guidata(hObject);
set(handles.eGainMin,'String',data.PlotPref.caxis(1));
set(handles.eGainMax,'String',data.PlotPref.caxis(2));
axes(handles.axMain);
caxis(data.PlotPref.caxis);
drawnow;
% --------------------------------------------------------------------
function KeyPressFcn_Callback(hObject, eventdata, handles)
data=guidata(hObject);
Key=get(gcf,'CurrentCharacter');
%SegymatVerbose(['GUI : KeyPressFcn : ',num2str(double(Key)),' ',char(Key)],20)
%disp(char(Key));
%disp(double(Key));
%%%%%%%%%%%
% GAIN
%if (Key=='+'),
if ((double(Key)==30)|(double(Key)==43)|(double(Key)==115))
data.PlotPref.caxis=data.PlotPref.caxis./(1.2);
guidata(hObject,data);
UpdateGain(hObject, eventdata, handles) ;
end
%if (Key=='-');
if ((double(Key)==31)|(double(Key)==45)|(double(Key)==120))
data.PlotPref.caxis=data.PlotPref.caxis.*(1.2);
guidata(hObject,data);
UpdateGain(hObject, eventdata, handles) ;
end
%% SHOW PREFS
if (lower(Key)=='h')
if isfield(data.PlotPref,'Show')==0, data.PlotPref.Show=1;end
data.PlotPref.Show=1-data.PlotPref.Show;
guidata(hObject,data);
fMain_ResizeFcn(hObject,[],handles);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% ZOOM ON MAIN AX
if isfield(data,'zoomfac')==0
data.zoomfac=1.5;
guidata(hObject,data);
end
zoom_in_keys=[29,97]; % ARROW RIGHT OR 'a'
zoom_out_keys=[28,122]; % ARROW LEFT OR 'z'
if isempty(Key)==1
Key=0;
end
try
if find(double(Key)==zoom_in_keys);
zoom(data.zoomfac)
UpdateTopPlot(hObject, eventdata, handles)
UpdateBotPlot(hObject, eventdata, handles)
end
catch
SegymatVerbose(sprintf('%s : failed to zoom',mfilename))
%keyboard;
end
if find(double(Key)==zoom_out_keys);
zoom(-data.zoomfac)
UpdateTopPlot(hObject, eventdata, handles)
UpdateBotPlot(hObject, eventdata, handles)
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% MOVE
if isfield(data,'movefac')==0
% Movefac=1; move in stepos of size of window
% Movefac=0.5; move in steps of half-size of window
data.movefac=.02;
guidata(hObject,data);
end
if (double(Key)>=49)&(double(Key)<=117), % NUM PAD
go_left_keys=[52,117]; % 2,j
go_right_keys=[54,111]; % 2,j
go_down_keys=[50,107]; % 2,j
go_up_keys=[56]; % 2,j
xlim=get(handles.axMain,'Xlim');
ylim=get(handles.axMain,'Ylim');
wx=(xlim(2)-xlim(1)).*data.movefac;
wy=(ylim(2)-ylim(1)).*data.movefac;
if (find(go_up_keys==double(Key))), set(handles.axMain,'Ylim',ylim-wy); end % 8
if (find(go_down_keys==double(Key))), set(handles.axMain,'Ylim',ylim+wy); end % 2
if (find(go_left_keys==double(Key))), set(handles.axMain,'Xlim',xlim-wx); end % 4
if (find(go_right_keys==double(Key))), set(handles.axMain,'Xlim',xlim+wx); end % 6
if (double(Key)==49), % 1
set(handles.axMain,'Ylim',ylim+wy);
set(handles.axMain,'Xlim',xlim-wx);
end % 1
if (double(Key)==51), % 3
set(handles.axMain,'Ylim',ylim+wy);
set(handles.axMain,'Xlim',xlim+wx);
end % 3
if (double(Key)==55), % 7
set(handles.axMain,'Ylim',ylim-wy);
set(handles.axMain,'Xlim',xlim-wx);
end % 7
if (double(Key)==57), % 9
set(handles.axMain,'Ylim',ylim-wy);
set(handles.axMain,'Xlim',xlim+wx);
end % 9
if (double(Key)==53), % 5
axes(handles.axMain)
zoom out;
end % 5
xlim_after=get(handles.axMain,'Xlim');
if (sum(xlim==xlim_after)<2)
UpdateTopPlot(hObject, eventdata, handles)
UpdateBotPlot(hObject, eventdata, handles)
end
end
%
% IO FUNCTIONS
%
% --------------------------------------------------------------------
function mFileOpen_Callback(hObject, eventdata, handles)
% hObject handle to mFileOpen (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
try
data=guidata(hObject);
if isfield(data,'SegyFile');
segyfile=DIAOpenSEGY(data.SegyFile);
else
segyfile=DIAOpenSEGY;
end
fReadSegy_Callback(hObject, eventdata, handles,segyfile);
catch
end
% --------------------------------------------------------------------
function mOpenFileFast_Callback(hObject, eventdata, handles)
% hObject handle to mOpenFileFast (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
try
[segyfile.filename,segyfile.pathname]=uigetfile( ...
{'*.segy;*.SEGY;*.SEGY;*.sgy','All Segy files'; ...
'*.su;*.SU;*.sU;*.Su','All SU files'; ...
'*','All Files'},...
'Pick A SEGY file');
fReadSegy_Callback(hObject, eventdata, handles,segyfile);
catch
end
% --------------------------------------------------------------------
function fReadSegy_Callback(hObject, eventdata, handles,segyfile);
data=guidata(hObject);
try
[dpath,dfile,dsuffix]=fileparts(segyfile.filename);
if (strcmp(lower(dsuffix),'.su'))
[data.SegyData,data.SegyTraceHeaders,data.SegyHeader]=ReadSu(fullfile(segyfile.pathname,segyfile.filename));
else
if isfield(segyfile,'JUMP');
k=0;
try
if segyfile.JUMP.enable==1
k=k+1;v{k}='jump';
k=k+1;v{k}=segyfile.JUMP.jump;
end
if segyfile.TIMERANGE.enable==1
k=k+1;v{k}='trange';
k=k+1;v{k}=segyfile.TIMERANGE.min;
k=k+1;v{k}=segyfile.TIMERANGE.max;
end
if segyfile.TRACEHEADER.enable==1
k=k+1;v{k}='minmax';
k=k+1;v{k}=segyfile.TRACEHEADER.name;
k=k+1;v{k}=segyfile.TRACEHEADER.min;
k=k+1;v{k}=segyfile.TRACEHEADER.max;
end
catch
SegymatVerbose(sprintf('%s : failed to make use of headers for reading',mfilename))
%keyboard
end
if k>0
[data.SegyData,data.SegyTraceHeaders,data.SegyHeader]=ReadSegy(fullfile(segyfile.pathname,segyfile.filename),v);
else
[data.SegyData,data.SegyTraceHeaders,data.SegyHeader]=ReadSegy(fullfile(segyfile.pathname,segyfile.filename));
end
else
[data.SegyData,data.SegyTraceHeaders,data.SegyHeader]=ReadSegy(fullfile(segyfile.pathname,segyfile.filename));
end
end
if isempty(data.SegyData)
f = warndlg('No data was read !', 'ReadSegy warning', 'modal');
else
set(handles.fMain,'name',['SegyMAT : ',segyfile.filename])
data.SegyFile=segyfile;
data.SegyTime=[1:1:data.SegyHeader.ns].*data.SegyHeader.dt/1e+6;
data.SegyTrace=[1:length(data.SegyTraceHeaders)];
data.PlotPref.Show=1;
data.PlotPref.caxis=[min(data.SegyData(:)) max(data.SegyData(:))];
guidata(hObject,data);
fMain_ResizeFcn(hObject, eventdata, handles);
UpdatePrefs(hObject, eventdata, handles);
UpdatePlots(hObject, eventdata, handles);
end
catch
errordlg('An error occured while reading the SEGY file','Error reading SGY file','modal')
%keyboard
end
UpdateMenus(hObject, eventdata, handles);
% --------------------------------------------------------------------
function mFileSave_Callback(hObject, eventdata, handles)
% hObject handle to mFileSave (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
try
data=guidata(hObject);
file=fullfile(data.SegyFile.pathname,data.SegyFile.filename);
ButtonName=questdlg(['Are you sure you want to override :',file], ...
'Warning !!!', ...
'Yes','No','No');
if strcmp(ButtonName,'Yes')
[dpath,dfile,dsuffix]=fileparts(file);
if (strcmp(lower(dsuffix),'.su'))
WriteSuStructure(file,data.SegyHeader,data.SegyTraceHeaders,data.SegyData);
else
WriteSegyStructure(file,data.SegyHeader,data.SegyTraceHeaders,data.SegyData);
end
end
catch
errordlg('An error occured while writing SEGY file','Error writing SGY file','modal')
end
% --------------------------------------------------------------------
function mFileSaveAs_Callback(hObject, eventdata, handles)
% hObject handle to mFileSaveAs (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
try
data=guidata(hObject);
[segyfile.filename,segyfile.pathname]=uiputfile( ...
{'*.segy;*.SEGY;*.SEGY;*.sgy','All Segy files'; ...
'*.su;*.SU;*.sU;*.Su','All SU files'; ...
'*','All Files'},...
'Save as ');
file=fullfile(segyfile.pathname,segyfile.filename);
[dpath,dfile,dsuffix]=fileparts(file);
if (strcmp(lower(dsuffix),'.su'))
WriteSuStructure(file,data.SegyHeader,data.SegyTraceHeaders,data.SegyData);
else
WriteSegyStructure(file,data.SegyHeader,data.SegyTraceHeaders,data.SegyData);
end
catch
errordlg('An error occured while writing SEGY file','Error writing SGY file','modal')
end
% --------------------------------------------------------------------
function mHelp_Callback(hObject, eventdata, handles)
% hObject handle to mHelp (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% --------------------------------------------------------------------
function mHelpHelp_Callback(hObject, eventdata, handles)
% hObject handle to mHelpHelp (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
SegymatHelp('index')
% --------------------------------------------------------------------
function mHelpAbout_Callback(hObject, eventdata, handles)
% hObject handle to mHelpAbout (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
DIAAboutSegymat;
% --- Executes on button press in pbGainUp.
function pbGainUp_Callback(hObject, eventdata, handles)
% hObject handle to pbGainUp (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
data=guidata(hObject);
data.PlotPref.caxis=data.PlotPref.caxis./(1.2);
guidata(hObject,data);
UpdateGain(hObject, eventdata, handles) ;
Style=get(handles.popStyle,'Value'); % GET PLOTTING STYLE
if ((Style==2)|(Style==4|(Style==3)|(Style==5)))
UpdateMainPlot(hObject, eventdata, handles)
end
% --- Executes on button press in pbGainDown.
function pbGainDown_Callback(hObject, eventdata, handles)
% hObject handle to pbGainDown (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
data=guidata(hObject);
data.PlotPref.caxis=data.PlotPref.caxis.*(1.2);
guidata(hObject,data);
UpdateGain(hObject, eventdata, handles) ;
Style=get(handles.popStyle,'Value'); % GET PLOTTING STYLE
if ((Style==2)|(Style==4|(Style==3)|(Style==5)))
UpdateMainPlot(hObject, eventdata, handles)
end
% --- Executes during object creation, after setting all properties.
function eGainMin_CreateFcn(hObject, eventdata, handles)
% hObject handle to eGainMin (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc
set(hObject,'BackgroundColor','white');
else
set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end
function eGainMin_Callback(hObject, eventdata, handles)
% hObject handle to eGainMin (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of eGainMin as text
% str2double(get(hObject,'String')) returns contents of eGainMin as a double
data=guidata(hObject);
data.PlotPref.caxis(1)=str2double(get(hObject,'String'));
guidata(hObject,data);
UpdateGain(hObject, eventdata, handles);
% --- Executes during object creation, after setting all properties.
function eGainMax_CreateFcn(hObject, eventdata, handles)
% hObject handle to eGainMax (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc
set(hObject,'BackgroundColor','white');
else
set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end
function eGainMax_Callback(hObject, eventdata, handles)
% hObject handle to eGainMax (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of eGainMax as text
% str2double(get(hObject,'String')) returns contents of eGainMax as a double
data=guidata(hObject);
data.PlotPref.caxis(2)=str2double(get(hObject,'String'));
guidata(hObject,data);
UpdateGain(hObject, eventdata, handles);
% --- Executes during object creation, after setting all properties.
function popTop_CreateFcn(hObject, eventdata, handles)
% hObject handle to popTop (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: popupmenu controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc
set(hObject,'BackgroundColor','white');
else
set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end
% --- Executes on selection change in popTop.
function popTop_Callback(hObject, eventdata, handles)
% hObject handle to popTop (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: contents = get(hObject,'String') returns popTop contents as cell array
% contents{get(hObject,'Value')} returns selected item from popTop
SegymatVerbose(['GUI : Update popTOP'],20)
UpdateTopPlot(hObject, eventdata, handles)
% --- Executes during object creation, after setting all properties.
function popBot_CreateFcn(hObject, eventdata, handles)
% hObject handle to popBot (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: popupmenu controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc
set(hObject,'BackgroundColor','white');
else
set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end
% --- Executes on selection change in popBot.
function popBot_Callback(hObject, eventdata, handles)
% hObject handle to popBot (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: contents = get(hObject,'String') returns popBot contents as cell array
% contents{get(hObject,'Value')} returns selected item from popBot
SegymatVerbose(['GUI : Update popBOT'],20)
UpdateBotPlot(hObject, eventdata, handles)
% --- Executes during object creation, after setting all properties.
function popColormap_CreateFcn(hObject, eventdata, handles)
% hObject handle to popColormap (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: popupmenu controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc
set(hObject,'BackgroundColor','white');
else
set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end
% --- Executes on selection change in popColormap.
function popColormap_Callback(hObject, eventdata, handles)
% hObject handle to popColormap (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: contents = get(hObject,'String') returns popColormap contents as cell array
% contents{get(hObject,'Value')} returns selected item from popColormap
SegymatVerbose(['GUI : Update popColormap'],20)
data=guidata(hObject);
cmap=get(hObject,'String');
icmap=get(hObject,'value');
axes(handles.axMain);
colormap(cmap{icmap});
%%% zoom on;
% --- Executes during object creation, after setting all properties.
function popStyle_CreateFcn(hObject, eventdata, handles)
% hObject handle to popStyle (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: popupmenu controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc
set(hObject,'BackgroundColor','white');
else
set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end
% --- Executes on selection change in popStyle.
function popStyle_Callback(hObject, eventdata, handles)
% hObject handle to popStyle (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: contents = get(hObject,'String') returns popStyle contents as cell array
% contents{get(hObject,'Value')} returns selected item from popStyle
SegymatVerbose(['GUI : popStyle'],20)
UpdateMainPlot(hObject, eventdata, handles);
UpdateTopPlot(hObject, eventdata, handles)
UpdateBotPlot(hObject, eventdata, handles)
%
% MENUS
%
% --------------------------------------------------------------------
function UpdateMenus(hObject, eventdata, handles)
SegymatVerbose(['GUI : Update Menus'],20)
data=guidata(hObject);
if isfield(data,'SegyData')==0
set(handles.mEdit,'Visible','Off')
else
set(handles.mEdit,'Visible','On')
end
% --------------------------------------------------------------------
function mFile_Callback(hObject, eventdata, handles)
% hObject handle to mFile (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% --------------------------------------------------------------------
function mEdit_Callback(hObject, eventdata, handles)
% hObject handle to mEdit (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% --------------------------------------------------------------------
function mEditSH_Callback(hObject, eventdata, handles)
% hObject handle to mEditSH (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
data=guidata(hObject);
try
data.SegyHeader=GUIEditSegyHeader(data.SegyHeader);
guidata(hObject,data)
catch
end
% --------------------------------------------------------------------
function mEditSTH_Callback(hObject, eventdata, handles)
% hObject handle to mEditSTH (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
data=guidata(hObject);
try
data.SegyTraceHeaders=GUIEditSegyTraceHeader(data.SegyTraceHeaders);
guidata(hObject,data)
UpdateTopPlot(hObject, eventdata, handles)
UpdateBotPlot(hObject, eventdata, handles)
catch
SegymatVerbose('Something Went wrong calling GUISegyMat')
end
% --------------------------------------------------------------------
function mPlotXY_Callback(hObject, eventdata, handles)
% hObject handle to mPlotXY (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
data=guidata(hObject);
try
GUIPlotXY(data.SegyTraceHeaders);
catch
SegymatVerbose('Something Went wrong calling GUISegyMat')
end
% --------------------------------------------------------------------
function mplot_Callback(hObject, eventdata, handles)
% hObject handle to mplot (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% --------------------------------------------------------------------
function mEditTextualHeader_Callback(hObject, eventdata, handles)
% hObject handle to mEditTextualHeader (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
data=guidata(hObject);
try
data.SegyHeader=GUIEditTextualFileHeader(data.SegyHeader);
guidata(hObject,data)
catch
end
|
github
|
Abakumov/MLIB-master
|
DIAAboutSegymat.m
|
.m
|
MLIB-master/OTHER/SegyMAT/GUI/DIAAboutSegymat.m
| 3,129 |
utf_8
|
31dd15d94b44aaf08dbaaa262c7a3a85
|
function varargout = DIAAboutSegymat(varargin)
% DIAAboutSegymat Application M-file for DIAAboutSegymat.fig
% FIG = DIAABOUTSEGYMAT launch DIAAboutSegymat GUI.
% DIAABOUTSEGYMAT('callback_name', ...) invoke the named callback.
% Last Modified by GUIDE v2.0 06-May-2002 10:38:58
if nargin == 0 % LAUNCH GUI
fig = openfig(mfilename,'reuse');
% Generate a structure of handles to pass to callbacks, and store it.
handles = guihandles(fig);
guidata(fig, handles);
set(fig,'HandleVisibility','On')
[ver,releasedate]=SegymatVersion;
[rev]=SegymatRevision;
set(handles.tVersion,'String',ver)
set(handles.tReleaseDate,'String',releasedate)
set(handles.lbRevision,'String',rev)
set(fig,'HandleVisibility','CallBack')
set(handles.fAboutSegymat,'Visible','on')
% Wait for callbacks to run and window to be dismissed:
uiwait(fig);
if nargout > 0
varargout{1} = fig;
end
elseif ischar(varargin{1}) % INVOKE NAMED SUBFUNCTION OR CALLBACK
try
if (nargout)
[varargout{1:nargout}] = feval(varargin{:}); % FEVAL switchyard
else
feval(varargin{:}); % FEVAL switchyard
end
catch
disp(lasterr);
end
end
%| ABOUT CALLBACKS:
%| GUIDE automatically appends subfunction prototypes to this file, and
%| sets objects' callback properties to call them through the FEVAL
%| switchyard above. This comment describes that mechanism.
%|
%| Each callback subfunction declaration has the following form:
%| <SUBFUNCTION_NAME>(H, EVENTDATA, HANDLES, VARARGIN)
%|
%| The subfunction name is composed using the object's Tag and the
%| callback type separated by '_', e.g. 'slider2_Callback',
%| 'figure1_CloseRequestFcn', 'axis1_ButtondownFcn'.
%|
%| H is the callback object's handle (obtained using GCBO).
%|
%| EVENTDATA is empty, but reserved for future use.
%|
%| HANDLES is a structure containing handles of components in GUI using
%| tags as fieldnames, e.g. handles.figure1, handles.slider2. This
%| structure is created at GUI startup using GUIHANDLES and stored in
%| the figure's application data using GUIDATA. A copy of the structure
%| is passed to each callback. You can store additional information in
%| this structure at GUI startup, and you can change the structure
%| during callbacks. Call guidata(h, handles) after changing your
%| copy to replace the stored original so that subsequent callbacks see
%| the updates. Type "help guihandles" and "help guidata" for more
%| information.
%|
%| VARARGIN contains any extra arguments you have passed to the
%| callback. Specify the extra arguments by editing the callback
%| property in the inspector. By default, GUIDE sets the property to:
%| <MFILENAME>('<SUBFUNCTION_NAME>', gcbo, [], guidata(gcbo))
%| Add any extra arguments after the last argument, before the final
%| closing parenthesis.
% --------------------------------------------------------------------
function varargout = listbox1_Callback(h, eventdata, handles, varargin)
% --------------------------------------------------------------------
function varargout = pushbutton1_Callback(h, eventdata, handles, varargin)
uiresume
closereq
|
github
|
Abakumov/MLIB-master
|
myReadSegy.m
|
.m
|
MLIB-master/OTHER/ReadSegy/myReadSegy.m
| 17,770 |
utf_8
|
98d57dbfeab01b5e94ac631740299bea
|
% ReadSegy : Reads a SEG Y rev 1 formatted file
%
% Call :
% [Data,SegyTraceHeaders,SegyHeader]=ReadSegy(filename);
%
% To read time slice 0.5<t<5 :
% [Data,SegyTraceHeaders,SegyHeader]=ReadSegy(filename,'trange',.5,3);
% To read time trace number 100,110 and 150 :
% [Data,SegyTraceHeaders,SegyHeader]=ReadSegy(filename,'traces',[100 110 150]);
% Skip every 5th trace :
% [Data,SegyTraceHeaders,SegyHeader]=ReadSegy(filename,'jump',5);
% Read data in a CDP header range : 5000<cdp<5800 :
% (change cdp to any other valid TraceHeader value)
% [Data,SegyTraceHeaders,SegyHeader]=ReadSegy(filename,'minmax','cdp',5000,5800);
% Read only the header values (Data will return empty)
% [Data,SegyTraceHeaders,SegyHeader]=ReadSegy(filename,'SkipData',1);
%
% SEG-Y format revision number can be '0' (1975) or
% '100' (similar to '1') (2002).
% By default the SEG-Y format revision number is read in the
% binary header, but this can be overruled using :
% [Data,SegyTraceHeaders,SegyHeader]=ReadSegy(filename,'revision',0);
%
% Read using a specific Data Sample Format :
% Rev 0, IBM FLOATING POINT
% [Data,SegyTraceHeaders,SegyHeader]=ReadSegy(filename,'revision',0,'dsf',1);
% Rev 1, IEEE FLOATING POINT
% [Data,SegyTraceHeaders,SegyHeader]=ReadSegy(filename,'revision',1,'dsf',5);
%
% A SegyHeader can be forced on the SEG-Y file using :
% [Data,SegyTraceHeaders,SegyHeader]=ReadSegy(filename,'SegyHeader',SegyHeader);
% The SegyHeader can be obtain by GetSegyHeader(segyfilename), and
% then edited.
%
% To read using little endian :
% [Data,SegyTraceHeaders,SegyHeader]=ReadSegy(filename,'endian','l');
%
% Combine any combination of the above
% [Data,SegyTraceHeaders,SegyHeader]=ReadSegy(filename,'jump',1,'minmax','cdp',5300,5400);
%
%
% Plot the data using e.g.
% imagesc([SegyTraceHeaders.cdp],SegyHeader.time,Data);
% wiggle([SegyTraceHeaders.TraceNumber],SegyHeader.time,Data);
%
% (C) 2003-2004, Thomas Mejer Hansen, [email protected]
%
% Implemented using the syntax of the SEG-Y revised format :
% SEGY-Y rev 0, SEG-Y rev 1 as described in
% http://seg.org/publications/tech-stand/
%
% Extended Textual Header is not yet tested
% If you would like it implemented, please send me an SEGY file with
% that sort of information, as well as a description of the segy file
%
%
% (C) 2001-2004, Thomas Mejer Hansen, [email protected]/[email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
%
%
%
%
% 0.1 : INitial Release
% 0.2 : Added SkipData var, to skip reading of data.
% 0.3 : May 01, 2002
% Added ability to read in ever 'jump' traces.
% Added ability to read in time range.
% Added abiliy to read in header range (ex. mincdp to maxcdp).
%
% TODO : WHEN READING ONLY PART OF DATASET MAKE SURE TO ADJUST THE SEGY
% HEADER ACCORDINGLY !!!!!!
function [Data,SegyTraceHeaders,SegyHeader,HeaderInfo]=ReadSegy(filename,varargin);
if isoctave
doWaitBar=0; % [1] show progress bar gui
mfilename='ReadSegy';
else
doWaitBar=0;
mfilename='ReadSegy';
end
dsf=[];
revision=[];
endian_tight=[];
tmin=[];tmax=[];
headermin=[];headermax=[];header=[];
jump=[];
SkipData=[];
endian='ieee-le'; % Big Endian is default
SegymatVerbose([mfilename,' : reading ',filename])
if ~(exist(filename)==2'),
SegymatVerbose([mfilename,' : ', filename,' does not exist !'])
Data=[];SegyTraceHeaders=[];SegyHeader=[];HeaderInfo=[];
return
end
% IF ONLY 'filename', AND one outpuet HAS BEEN
% SPECIFIED AS IN/OUTPUT, THEN USE THE FAST
% ALGORITHM FOR READING.
if (nargin==1)&(nargout==1)
[Data]=ReadSegyFast(filename);
return
end
SegymatVerbose([mfilename,' - Checking Varargin'],90)
ninput=nargin;
% NEXT TWO LINES TO ENUSRE THAT VARARGIN CAN BE PASSED TO FUNCTION
if ninput==2
% CALL USING VARARGIN
ninput=1+length(varargin{1});
varargin=varargin{1};
else
% DIRECT CALL
ninput=length(varargin);
end
% TRANSFORM VARARGING INTO PARAMETERS
traces=[];
cargin=1;
while (cargin<ninput)
SegymatVerbose([mfilename,' - Converting varargin, ',num2str(cargin)],90)
if strcmp(varargin{cargin},'jump')
cargin=cargin+1;
eval(['jump=',num2str(varargin{cargin}),';']);
SegymatVerbose(['JUMP : Read only every ',num2str(jump),'th trace'])
end
if strcmp(varargin{cargin},'traces')
cargin=cargin+1;
traces=varargin{cargin};
SegymatVerbose(['TRACES : Read only every ',num2str(jump),'th trace'])
end
if strcmp(varargin{cargin},'minmax')
cargin=cargin+1;
eval(['header=''',varargin{cargin},''';']);
cargin=cargin+1;
eval(['headermin=',num2str(varargin{cargin}),';']);
cargin=cargin+1;
eval(['headermax=',num2str(varargin{cargin}),';']);
SegymatVerbose(['MIN MAX : Using header ',header,' from ',num2str(headermin),' to ',num2str(headermax)])
h=ReadSegyTraceHeaderValue(filename,'key',header);
minmax_traces=find(h>=headermin & h<=headermax);
if isempty(traces)
traces=minmax_traces;
else
traces=intersect(traces,minmax_traces);
end
end
if strcmp(varargin{cargin},'trange')
cargin=cargin+1;
eval(['tmin=',num2str(varargin{cargin}),';']);
cargin=cargin+1;
eval(['tmax=',num2str(varargin{cargin}),';']);
SegymatVerbose(['TRANGE : tmin=',num2str(tmin),' tmax=',num2str(tmax)])
end
% ENDIAN FORMAT
if strcmp(varargin{cargin},'endian')
cargin=cargin+1;
eval(['endian_tight=varargin{cargin};'])
if endian_tight=='l',
SegymatVerbose(['USING LITTLE ENDIAN TYPE'])
endian='ieee-le';
else
SegymatVerbose(['USING BIG ENDIAN TYPE'])
end
end
if strcmp(varargin{cargin},'revision')
cargin=cargin+1;
eval(['revision=',num2str(varargin{cargin}),';']);
SegymatVerbose(['USING REVISION : rev=',num2str(revision)])
end
if strcmp(varargin{cargin},'dsf')
cargin=cargin+1;
eval(['dsf=',num2str(varargin{cargin}),';']);
SegymatVerbose(['USING Data Sample Format : dsf=',num2str(dsf)])
end
if strcmp(varargin{cargin},'SkipData')
cargin=cargin+1;
eval(['SkipData=',num2str(varargin{cargin}),';']);
SegymatVerbose(['SKIPPNG DATA - READING ONLY HEADERS'])
end
if strcmp(varargin{cargin},'SegyHeader')
cargin=cargin+1;
SegyHeader=varargin{cargin};
SegymatVerbose(['USING LOADED SEGYHEADER'])
end
cargin=cargin+1;
end
if isempty(SkipData)==1,
SegymatVerbose([mfilename,' : Skip data is not set (defautls to 0)'],90)
SkipData=0; % [0] READ ONLY HEADER VALUES, [1] READ IN ALL DATA
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% OPEN FILE HANDLE
if exist('endian')==1,
SegymatVerbose([mfilename,' : ENDIAN : ',endian],1)
segyid = fopen(filename,'r',endian);
else
endian='ieee-be';
SegymatVerbose([mfilename,' : ENDIAN SET TO ',endian],0)
segyid = fopen(filename,'r','ieee-be'); % ALL DISK FILES ARE IN BIG
end % ENDIAN FORMAT, ACCORDING TO
% SEGY Y rev 1
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% BINARY HEADERS
if exist('SegyHeader')==0
SegyHeader=GetSegyHeader(segyid);
else
SegymatVerbose([mfilename,' - Using supplied SegyHeader'])
end
% APPLY CHANGES TO SEGY HEADER IF NEEDE
if isempty(revision)==0,
SegyHeader.SegyFormatRevisionNumber=revision;
SegymatVerbose([mfilename,' - Manually set SEG-Y revision to ',num2str(revision)])
end
if isempty(dsf)==0,
SegyHeader.DataSampleFormat=dsf;
end
% JUST SOME INFORMATION TO WRITE TO SCREEN :
Revision=SegyHeader.SegyFormatRevisionNumber;
if Revision>0, Revision=1; end
if (SegyHeader.DataSampleFormat>length(SegyHeader.Rev(Revision+1).DataSampleFormat));
SegymatVerbose([mfilename,' : WARNING : YOU HAVE SELECTED (OR THE FILE IS FORMATTED SUCH THAT) A DATASAMPLE FORMAT THAT IS NOT DEFINED. \nREMEBER IEEE IS NOT SPECIFIED IN THE SEGY REV0 STANDARD !'])
if (Revision==0)
SegymatVerbose([mfilename,' : TRYING TO USE REVISION 1 AS OPPOSED TO REVISION 0'])
Revision=1;
if (SegyHeader.DataSampleFormat>length(SegyHeader.Rev(Revision+1).DataSampleFormat));
SegymatVerbose([mfilename,' : FATAL ERROR : STILL THE DATASAMPLE FORMAT IS NOT SUPPRTED - EXITING (Report error to [email protected])'])
else
SegymatVerbose([mfilename,' : APPARENT SUCCES CHANING FROM Revision 0 to 1 - Continuing'])
SegyHeader.SegyFormatRevisionNumber=1; % FORCING REVISION TO BE 1 !!!
end
end
end
FormatName=SegyHeader.Rev(Revision+1).DataSampleFormat(SegyHeader.DataSampleFormat).name;
Format=SegyHeader.Rev(Revision+1).DataSampleFormat(SegyHeader.DataSampleFormat).format;
BPS=SegyHeader.Rev(Revision+1).DataSampleFormat(SegyHeader.DataSampleFormat).bps;
txt=['SegyRevision ',sprintf('%0.4g',Revision),', ',FormatName,'(',num2str(SegyHeader.DataSampleFormat),')'];
ns=SegyHeader.ns;
% YOU CAN FORCE FixedLengthTraceFlag=1;
% This will make the code much faster (especially when using
% the 'jump' option) but reading data with varying trace lengt will fail.
% It is here since many old data sets with Constant trace length
% has FixedLengthTraceFlag=0;
%
% As of version 1.01 this has been enable by default.
% Change the variable below to '0' if you do not want this behaviour
%
SegyHeader.FixedLengthTraceFlag=1;
SegymatVerbose([mfilename,' : Reading Data'],90);
% MAKE USE OF ReadSegyTrace to quickly read specific traces
%if ~isempty(traces)
% [Data,SegyTraceHeaders,SegyHeader]=ReadSegyTrace(filename,traces,SegyHeader);
% HeaderInfo=[];
% return;
%end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% READ DATA
%Segy=fread(segyid,4000,'float32');
fseek(segyid,0,'eof'); DataEnd=ftell(segyid);
fseek(segyid,0,'eof'); DataEnd=ftell(segyid);
DataStart=3600+3200*SegyHeader.NumberOfExtTextualHeaders;
fseek(segyid,DataStart,'bof'); % Go to the beginning of the file
fseek(segyid,DataStart,'bof'); % Go to the beginning of the file
ntraces=round((DataEnd-DataStart)./(240+(SegyHeader.ns)*(BPS/8)));
SegymatVerbose(['Number of Samples Per Trace=',num2str(SegyHeader.ns)])
SegymatVerbose(['Number of Traces=',num2str(ntraces)])
if (ntraces~=round(ntraces))
SegymatVerbose(['Trace lengths seems to vary. trying to read the file anyway'])
end
existJump=~isempty(jump);
existHeader=~isempty(header);
existTmin=~isempty(tmin);
existTmax=~isempty(tmax);
out_ntraces=ntraces;
if existJump==1, out_ntraces=ceil(ntraces/jump);end
if ~isempty(traces), out_ntraces=length(traces);end
dwaitbar=10;
if DataEnd./jump>1e+6, dwaitbar=10; end
if DataEnd./jump>1e+7, dwaitbar=50; end
if DataEnd./jump>1e+8, dwaitbar=200; end
traceinfile=0;
outtrace=0;
tic;
toc_old=toc;
if doWaitBar==1;
hw=waitbar(0,['Reading Segy - ',txt]);
end
% LOOP OVER TRACES
t0=now;
tlast=t0;
pos0=ftell(segyid);
while (~(ftell(segyid)>=DataEnd))
usetrace=1; % DEFAULT USING TRACE WHEN [1].
traceinfile=traceinfile+1;
if ~isempty(traces);
if (traceinfile>length(traces))
break
else
traceskip=240+(BPS/8)*SegyHeader.ns;
skip=DataStart+(traces(traceinfile)-1)*traceskip;
fseek(segyid,skip,'bof');
end
end
ishow=10000;
itime=1/(24*3600)*2; % Min time between verbose info to screen
if (((traceinfile/ishow)==round(traceinfile/ishow))&((now-tlast)>itime)),
tnow=now;
tlast=tnow;
posnow=ftell(segyid);
tend=t0+DataEnd.*(tnow-t0)./(posnow-pos0);
tleft=(tend-tnow)*3600*24;
txt=sprintf('Reading trace %d/%d, (%5.0fs left) (est end %s)',traceinfile,ntraces,tleft,datestr(tend));
toc_old=toc;
SegymatVerbose(txt)
end
TraceStart=ftell(segyid);
% IF 'JUMP' IS SET THEN CHECK IF THIS TRACE SHOULD BE SKIPPED
if existJump==1
if (traceinfile/jump)~=round(traceinfile/jump), usetrace=0; end
end
if ((usetrace==0)&(SegyHeader.FixedLengthTraceFlag==1)),
% SKIP FORWARD IN FILE'
skip=240+(BPS/8)*SegyHeader.ns;
fseek(segyid,skip,'cof');
SegymatVerbose([num2str(traceinfile),' - SKIPPING TRACE ... ',num2str(outtrace)],2)
elseif (SegyHeader.FixedLengthTraceFlag==0)
SegymatVerbose(sprintf('Using Fixed Length Trace as SegyHeader.FixedLengthTraceFlag=0',traceinfile),10);
SingleSegyTraceHeaders=GetSegyTraceHeader(segyid,TraceStart,Format,SegyHeader.ns,[]);
SingleSegyData.data=GetSegyTraceData(segyid,SingleSegyTraceHeaders.ns,SegyHeader);
else
SingleSegyTraceHeaders=GetSegyTraceHeader(segyid,TraceStart,Format,SegyHeader.ns,[]);
SingleSegyData.data=GetSegyTraceData(segyid,SegyHeader.ns,SegyHeader);
if SingleSegyTraceHeaders.TraceNumber<1
SingleSegyTraceHeaders.TraceNumber=traceinfile;
SegymatVerbose(sprintf('TraceNumber malformatetd. Setting TraceNumber=%d',traceinfile),10);
end
SegymatVerbose(sprintf('ns=%d, Trace in line : %d, Trace in file : %d, ns=%10.5f dt=%10.5f',SingleSegyTraceHeaders.ns,SingleSegyTraceHeaders.TraceSequenceLine,SingleSegyTraceHeaders.TraceSequenceFile,SingleSegyTraceHeaders.ns,SingleSegyTraceHeaders.dt),10)
end
% IF HEADER MIN MAX HAS BEEN CHOSEN, THEN CHECK THAT TRACE IS GOOD ENOUGH
if ((existHeader==1)&(usetrace==1))
headervalue=getfield(SingleSegyTraceHeaders,header);
if ((headervalue<headermin)|(headervalue>headermax))
usetrace=0;
end
end
% USE THIS TRACE IF usetrace=1 !!
if usetrace==1,
%% IF TIME RANGE IS SPECIFIED, THEN EXTRACT THIS
if (existTmin==1)&(existTmax==1)
% NEXT LINE SHOULD CONSIDER THAT ns in Trace and Segy Header
% could vary !!!
origtrange=[1:1:SegyHeader.ns].*SegyHeader.dt.*1e-6+SingleSegyTraceHeaders.DelayRecordingTime.*1e-3;
gooddata=find(origtrange>tmin & origtrange<tmax);
SingleSegyData.data=SingleSegyData.data(gooddata);
% CHECK NEXT LINE TAHT DelatRec... is in micro seconds
SingleSegyTraceHeaders.DelayRecordingTime=tmin.*1e+3;
SingleSegyTraceHeaders.ns=length(gooddata);
ns=length(gooddata); % for use below
end
outtrace=outtrace+1;
if (outtrace==1),
% Preallocate RAM
ta1=now;
SegymatVerbose(sprintf('Pre allocating RAM ntraces=%d out_traces=%d',ntraces,out_ntraces));
SegyData=repmat(struct('data',zeros(ns,1)),1,out_ntraces);
SegyTraceHeaders=repmat(SingleSegyTraceHeaders,1,out_ntraces);
%whos SegyData SegyTraceHeaders
%save T1
ta2=now;
t0=t0+ta2-ta1;
end
SegyData(outtrace).data=SingleSegyData.data;
SegyTraceHeaders(outtrace)=SingleSegyTraceHeaders;
if doWaitBar==1,
if ((outtrace/dwaitbar)==round(outtrace/dwaitbar))
waitbar(ftell(segyid)/DataEnd,hw);
end
end
end
end
%save T2
%whos SegyData SegyTraceHeaders
if outtrace==0
SegymatVerbose(sprintf('%s : No traces read!',mfilename));
SegyTraceHeaders=[];
Data=[];
return
end
if doWaitBar==1
try
close(hw);
end
end
SegymatVerbose([mfilename,' : Elapsed time ',num2str(toc),' ended at ',datestr(now)]);
t=outtrace;
% Write time to SegyHeader
SegyHeader.ns=ns;
SegyHeader.time=[1:1:SegyHeader.ns].*SegyHeader.dt./1e+6+SegyTraceHeaders(1).DelayRecordingTime./1e+3;
% Make sure that only read SegyTraceHEaders are returned
if outtrace~=out_ntraces
SegyTraceHeaders=SegyTraceHeaders(1:outtrace);
end
% MOVE DATA from SegyData.data to a regular variable
% THIS STEP COULD BE AVOIDED WHEN FixedTraceLength=1, which is almost
% allways the case... Should speed up things and reduce memory reqs.
if SkipData==1,
Data=[];
else
try
Data=[SegyData(1:outtrace).data];
catch
Data=zeros(ns,outtrace);
for i=1:outtrace
try
Data(:,i)=SegyData(i).data;
catch
errmsg=lasterr;
if isempty(SegyData(i).data)
errmsg='Empty data in trace';
elseif (strfind(errmsg, 'In an assignment A(:,matrix) = B, the number of rows in A and B'))
nns=length(SegyData(i).data);
if nns<ns
errmsg='Length of trace varies - padding with zeros';
Data(1:nns,i)=SegyData(i).data;
else
errmsg='Length of trace varies - truncating';
Data(:,i)=SegyData(i).data(1:ns);
end
end
SegymatVerbose(sprintf('Had a problem at trace %d : %s',i,errmsg))
end
end
end
end
|
github
|
Abakumov/MLIB-master
|
seg2_read.m
|
.m
|
MLIB-master/OTHER/SEG2/seg2_read.m
| 5,996 |
utf_8
|
c5db925c2bba5700b2d15a7c94ef1a94
|
% SEG2_READ - Read in a file in SEG-2 format
% Version 0.9
% Usage:
%
% [FDStrings,nTraces,TDStrings,TraceData]=seg2_read(fname)
% read data and header from file 'fname'.
%
% Outputs:
% FDStrings - cell array of strings in the File Description Header
% nTraces - number of traces read
% TDStrings - cell array of cell arrays of the Trace Description strings
% (e.g., TDStrings{2}{3} is the third string in the second trace)
% TraceData - cell array of column vectors containing the data
% (e.g., TraceData{3} is the third trace).
%
% Cell arrays are used in the output to allow different trace lengths.
% Note: because of widespread non-compliance to the SEG-2 standard in
% field data no attempt is made to extract meaning from the header strings.
% This is left to a higher level program, probably on a case by case basis.
%
% (C) James Wookey, University of Bristol, 2008.
% Reference: SEG-2 standard: http://www.seg.org/publications/tech-stand/seg_2.pdf
% This software is distributed under the term of the BSD free software license.
%
% Copyright:
% (c) 2003-2008, James Wookey, University of Bristol
%
% All rights reserved.
%
% * Redistribution and use in source and binary forms, with or without
% modification, are permitted provided that the following conditions are
% met:
%
% * Redistributions of source code must retain the above copyright notice,
% this list of conditions and the following disclaimer.
%
% * Redistributions in binary form must reproduce the above copyright
% notice, this list of conditions and the following disclaimer in the
% documentation and/or other materials provided with the distribution.
%
% * Neither the name of the copyright holder nor the names of its
% contributors may be used to endorse or promote products derived from
% this software without specific prior written permission.
%
%
% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
% "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
% LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
% A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
% OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
% SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
% LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
% DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
% THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
% (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
% OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
function [FDStrings,nTraces,TDStrings,TraceData]=seg2_read(fname) ;
if nargout~=4, error('Wrong number of output arguments supplied.'), end ;
fid=fopen(fname,'r') ;
% read identifier block
endianFormat='l' ;
byteCount = 0 ;
id=fread(fid,1,'int16',0,endianFormat) ;
if id==14933
% ** format is little endian (do nothing)
elseif id==21818
% ** format is big endian
endianFormat='b' ;
else
% ** identifier is invalid
error('Bad identifier at SEG-2 file start, can''t determine format');
end
revno=fread(fid,1,'int16',0,endianFormat) ;
SizeTPSubBlock=fread(fid,1,'int16',0,endianFormat);
if rem(SizeTPSubBlock,4)~=0, error('Bad size for TPSubBlock'); ,end;
nTP = SizeTPSubBlock/4 ;
nTraces=fread(fid,1,'int16',0,endianFormat) ;
i=fread(fid,1,'int8',0,endianFormat) ;
code=fread(fid,[1 2],'int8',0,endianFormat) ;
strTermCode = code(1:i) ;
strTermChar = char(code(1:i)) ;
i=fread(fid,1,'int8',0,endianFormat) ;
code=fread(fid,[1 2],'int8',0,endianFormat) ;
lineTermCode = code(1:i) ;
lineTermChar = char(code(1:i)) ;
%% skip the unused part of the header
dump = fread(fid,18,'int8',0,endianFormat) ;
byteCount = byteCount+32;
TP_tmp=fread(fid,[1 nTP],'uint32',0,'l') ;
TP=TP_tmp(1:nTraces) ;
byteCount = byteCount+nTP*4;
nchar=TP(1)-32-nTP*4; % first offset minus the header
% ~order 806
code=fread(fid,[1 nchar],'int8',0,endianFormat) ;
byteCount = byteCount+nchar ;
% parse the string structure in here.
[FDStrings]=getstrings(code,strTermCode) ;
TDStrings = cell(1,nTraces);
TDnsamp = cell(1,nTraces) ;
TraceData = cell(1,nTraces) ;
for ii=1:nTraces
trace_header_id = fread(fid,1,'uint16',0,endianFormat) ;
if trace_header_id~=17442
error('Non-standards compliant SEG-2 format, cannot continue') ;
end
trace_header_size = fread(fid,1,'uint16',0,endianFormat) ;
trace_size = fread(fid,1,'uint32',0,endianFormat) ;
nsamp = fread(fid,1,'uint32',0,endianFormat) ;
TDnsamp{ii} = nsamp ;
format_code = fread(fid,1,'uint8',0,endianFormat) ;
if format_code~=4
error('Sorry, only 32 floating point data is currently supported')
end
dump = fread(fid,19,'uint8',0,endianFormat) ;
code=fread(fid,[1 trace_header_size-32],'int8',0,endianFormat);
% parse the string structure in here.
[TDStrings{ii}]=getstrings(code,strTermCode);
byteCount = byteCount+trace_header_size;
trace=fread(fid,[1 nsamp],'float32',0,endianFormat) ;
TraceData{ii}=trace ;
byteCount = byteCount + nsamp*4;
end
fclose(fid);
return
function [STR]=getstrings(code,strTermCode)
% first use the string term char in order to split
strEndsR=find(code==strTermCode);
strStartsR=[1 strEndsR(1:(length(strEndsR)-1))+1];
strEndsR = strEndsR - 1;
strLengthsR = strEndsR - strStartsR;
% dump any zero length strings
[strLengths ind]=find(strLengthsR>0);
strStarts = strStartsR(ind);
strEnds = strEndsR(ind);
nstr = length(strStarts);
STR = cell(1,nstr) ;
for istr=1:nstr
STR{istr} = char(code(strStarts(istr):strEnds(istr)));
end
|
github
|
Abakumov/MLIB-master
|
freezeColors.m
|
.m
|
MLIB-master/OTHER/Unfreeze_Colors/freezeColors/freezeColors.m
| 9,785 |
utf_8
|
c7342ab3baeb27df3ec6aa65d728966b
|
function freezeColors(varargin)
% freezeColors Lock colors of plot, enabling multiple colormaps per figure. (v2.3)
%
% Problem: There is only one colormap per figure. This function provides
% an easy solution when plots using different colomaps are desired
% in the same figure.
%
% freezeColors freezes the colors of graphics objects in the current axis so
% that subsequent changes to the colormap (or caxis) will not change the
% colors of these objects. freezeColors works on any graphics object
% with CData in indexed-color mode: surfaces, images, scattergroups,
% bargroups, patches, etc. It works by converting CData to true-color rgb
% based on the colormap active at the time freezeColors is called.
%
% The original indexed color data is saved, and can be restored using
% unfreezeColors, making the plot once again subject to the colormap and
% caxis.
%
%
% Usage:
% freezeColors applies to all objects in current axis (gca),
% freezeColors(axh) same, but works on axis axh.
%
% Example:
% subplot(2,1,1); imagesc(X); colormap hot; freezeColors
% subplot(2,1,2); imagesc(Y); colormap hsv; freezeColors etc...
%
% Note: colorbars must also be frozen. Due to Matlab 'improvements' this can
% no longer be done with freezeColors. Instead, please
% use the function CBFREEZE by Carlos Adrian Vargas Aguilera
% that can be downloaded from the MATLAB File Exchange
% (http://www.mathworks.com/matlabcentral/fileexchange/24371)
%
% h=colorbar; cbfreeze(h), or simply cbfreeze(colorbar)
%
% For additional examples, see test/test_main.m
%
% Side effect on render mode: freezeColors does not work with the painters
% renderer, because Matlab doesn't support rgb color data in
% painters mode. If the current renderer is painters, freezeColors
% changes it to zbuffer. This may have unexpected effects on other aspects
% of your plots.
%
% See also unfreezeColors, freezeColors_pub.html, cbfreeze.
%
%
% John Iversen ([email protected]) 3/23/05
%
% Changes:
% JRI ([email protected]) 4/19/06 Correctly handles scaled integer cdata
% JRI 9/1/06 should now handle all objects with cdata: images, surfaces,
% scatterplots. (v 2.1)
% JRI 11/11/06 Preserves NaN colors. Hidden option (v 2.2, not uploaded)
% JRI 3/17/07 Preserve caxis after freezing--maintains colorbar scale (v 2.3)
% JRI 4/12/07 Check for painters mode as Matlab doesn't support rgb in it.
% JRI 4/9/08 Fix preserving caxis for objects within hggroups (e.g. contourf)
% JRI 4/7/10 Change documentation for colorbars
% Hidden option for NaN colors:
% Missing data are often represented by NaN in the indexed color
% data, which renders transparently. This transparency will be preserved
% when freezing colors. If instead you wish such gaps to be filled with
% a real color, add 'nancolor',[r g b] to the end of the arguments. E.g.
% freezeColors('nancolor',[r g b]) or freezeColors(axh,'nancolor',[r g b]),
% where [r g b] is a color vector. This works on images & pcolor, but not on
% surfaces.
% Thanks to Fabiano Busdraghi and Jody Klymak for the suggestions. Bugfixes
% attributed in the code.
% Free for all uses, but please retain the following:
% Original Author:
% John Iversen, 2005-10
% [email protected]
appdatacode = 'JRI__freezeColorsData';
[h, nancolor] = checkArgs(varargin);
%gather all children with scaled or indexed CData
cdatah = getCDataHandles(h);
%current colormap
cmap = colormap;
nColors = size(cmap,1);
cax = caxis;
% convert object color indexes into colormap to true-color data using
% current colormap
for hh = cdatah',
g = get(hh);
%preserve parent axis clim
parentAx = getParentAxes(hh);
originalClim = get(parentAx, 'clim');
% Note: Special handling of patches: For some reason, setting
% cdata on patches created by bar() yields an error,
% so instead we'll set facevertexcdata instead for patches.
if ~strcmp(g.Type,'patch'),
cdata = g.CData;
else
cdata = g.FaceVertexCData;
end
%get cdata mapping (most objects (except scattergroup) have it)
if isfield(g,'CDataMapping'),
scalemode = g.CDataMapping;
else
scalemode = 'scaled';
end
%save original indexed data for use with unfreezeColors
siz = size(cdata);
setappdata(hh, appdatacode, {cdata scalemode});
%convert cdata to indexes into colormap
if strcmp(scalemode,'scaled'),
%4/19/06 JRI, Accommodate scaled display of integer cdata:
% in MATLAB, uint * double = uint, so must coerce cdata to double
% Thanks to O Yamashita for pointing this need out
idx = ceil( (double(cdata) - cax(1)) / (cax(2)-cax(1)) * nColors);
else %direct mapping
idx = cdata;
%10/8/09 in case direct data is non-int (e.g. image;freezeColors)
% (Floor mimics how matlab converts data into colormap index.)
% Thanks to D Armyr for the catch
idx = floor(idx);
end
%clamp to [1, nColors]
idx(idx<1) = 1;
idx(idx>nColors) = nColors;
%handle nans in idx
nanmask = isnan(idx);
idx(nanmask)=1; %temporarily replace w/ a valid colormap index
%make true-color data--using current colormap
realcolor = zeros(siz);
for i = 1:3,
c = cmap(idx,i);
c = reshape(c,siz);
c(nanmask) = nancolor(i); %restore Nan (or nancolor if specified)
realcolor(:,:,i) = c;
end
%apply new true-color color data
%true-color is not supported in painters renderer, so switch out of that
if strcmp(get(gcf,'renderer'), 'painters'),
set(gcf,'renderer','zbuffer');
end
%replace original CData with true-color data
if ~strcmp(g.Type,'patch'),
set(hh,'CData',realcolor);
else
set(hh,'faceVertexCData',permute(realcolor,[1 3 2]))
end
%restore clim (so colorbar will show correct limits)
if ~isempty(parentAx),
set(parentAx,'clim',originalClim)
end
end %loop on indexed-color objects
% ============================================================================ %
% Local functions
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% getCDataHandles -- get handles of all descendents with indexed CData
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function hout = getCDataHandles(h)
% getCDataHandles Find all objects with indexed CData
%recursively descend object tree, finding objects with indexed CData
% An exception: don't include children of objects that themselves have CData:
% for example, scattergroups are non-standard hggroups, with CData. Changing
% such a group's CData automatically changes the CData of its children,
% (as well as the children's handles), so there's no need to act on them.
error(nargchk(1,1,nargin,'struct'))
hout = [];
if isempty(h),return;end
ch = get(h,'children');
for hh = ch'
g = get(hh);
if isfield(g,'CData'), %does object have CData?
%is it indexed/scaled?
if ~isempty(g.CData) && isnumeric(g.CData) && size(g.CData,3)==1,
hout = [hout; hh]; %#ok<AGROW> %yes, add to list
end
else %no CData, see if object has any interesting children
hout = [hout; getCDataHandles(hh)]; %#ok<AGROW>
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% getParentAxes -- return handle of axes object to which a given object belongs
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function hAx = getParentAxes(h)
% getParentAxes Return enclosing axes of a given object (could be self)
error(nargchk(1,1,nargin,'struct'))
%object itself may be an axis
if strcmp(get(h,'type'),'axes'),
hAx = h;
return
end
parent = get(h,'parent');
if (strcmp(get(parent,'type'), 'axes')),
hAx = parent;
else
hAx = getParentAxes(parent);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% checkArgs -- Validate input arguments
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [h, nancolor] = checkArgs(args)
% checkArgs Validate input arguments to freezeColors
nargs = length(args);
error(nargchk(0,3,nargs,'struct'))
%grab handle from first argument if we have an odd number of arguments
if mod(nargs,2),
h = args{1};
if ~ishandle(h),
error('JRI:freezeColors:checkArgs:invalidHandle',...
'The first argument must be a valid graphics handle (to an axis)')
end
% 4/2010 check if object to be frozen is a colorbar
if strcmp(get(h,'Tag'),'Colorbar'),
if ~exist('cbfreeze.m'),
warning('JRI:freezeColors:checkArgs:cannotFreezeColorbar',...
['You seem to be attempting to freeze a colorbar. This no longer'...
'works. Please read the help for freezeColors for the solution.'])
else
cbfreeze(h);
return
end
end
args{1} = [];
nargs = nargs-1;
else
h = gca;
end
%set nancolor if that option was specified
nancolor = [nan nan nan];
if nargs == 2,
if strcmpi(args{end-1},'nancolor'),
nancolor = args{end};
if ~all(size(nancolor)==[1 3]),
error('JRI:freezeColors:checkArgs:badColorArgument',...
'nancolor must be [r g b] vector');
end
nancolor(nancolor>1) = 1; nancolor(nancolor<0) = 0;
else
error('JRI:freezeColors:checkArgs:unrecognizedOption',...
'Unrecognized option (%s). Only ''nancolor'' is valid.',args{end-1})
end
end
|
github
|
Abakumov/MLIB-master
|
l_resample.m
|
.m
|
MLIB-master/OTHER/SeisLab_10.0301/S4M/Geophysics_3.0/l_resample.m
| 5,775 |
utf_8
|
da3dc258340e425dce17483935fe29d5
|
function logout=l_resample(wlog,step,varargin)
% Function resamples all curves of a log. Gaps in log curves (NaNs) are
% interpolated prior to resampling (l_fill_gaps). Gaps are filled even
% if "step" is equal to wlog.step.
% Leading and/or trailing null values are ignored.
%
% Written by: E. Rietsch:
% Last updated: July 22, 2009: Keep field "null" even if there are no nulls.
%
% logout=l_resample(wlog,step,varargin)
% INPUT
% wlog input log
% step New step size. No default
% varargin cell array; the first element of the cell array is a keyword string,
% the following argument is a parameter.
% Accepted keywords are:
% 'option' Type of interpolation performed to avoid aliasing if the new
% step size is larger than the original step size.
% Possible values are: 'nearest','mean', and 'median'.
% 'median' can be used only if the new step size is an integer multiple of
% the step size of the input data. ('median' not yet implemented)
% 'nearest' is actually unrelated to the aliasing problem; the value
% assigned to a new depth is that of the nearest depth in the
% original log. This option is of particular interest for
% blocked logs as it preserves the blocky character.
% Default: {'option','mean'}
% OUTPUT
% logout resampled log
% UPDATE HISTORY
% December 23, 2005: Turn off warnings in "interp1" if NaN's are
% encountered
global S4M
% Set defaults for input parameters
param.option='mean';
% Decode and assign input arguments
param=assign_input(param,varargin);
if isfield(wlog,'null') % Fill gaps in log curves
wlog=l_fill_gaps(wlog);
end
if wlog.step == step
logout=wlog;
return
end
[nsamp,ncurves]=size(wlog.curves);
if nsamp <= 1
logout=wlog;
return
end
logout.first=ceil(wlog.first/step)*step;
logout.step=step;
depth=(logout.first:step:wlog.last)';
logout.last=depth(end);
logout.curves=zeros(length(depth),ncurves);
logout.curves(:,1)=depth;
if isfield(wlog,'null') && S4M.matlab_version >= 0 % Turn off warnings caused by NaN's in curves
warning('off','MATLAB:interp1:NaNinY')
end
switch param.option
case 'nearest'
logout.curves(:,2:end)=interp1(wlog.curves(:,1),wlog.curves(:,2:end),depth,'nearest');
case {'mean','median'}
if wlog.step > 0 % Handle uniformly sampled data
if wlog.step < step % New step size larger than original one
ratio=logout.step/wlog.step;
if strcmpi(param.option,'median')
disp(' Option "median" not yet implemented')
elseif strcmpi(param.option,'mean')
for ii=2:ncurves
temp=wlog.curves(:,ii);
idx=find(~isnan(temp));
if ~isempty(idx)
temp(idx)=mysmooth(temp(idx),ratio);
logout.curves(:,ii)=interp1(wlog.curves(:,1),temp,depth,'*linear');
else
logout.curves(:,ii)=NaN;
end
end
else
error([' Unknown option "',param.option,'"; check input arguments'])
end
else % New step size is smaller than the old one
for ii=2:ncurves
logout.curves(:,ii)=interp1(wlog.curves(:,1),wlog.curves(:,ii),depth,'*linear');
end
end
else % Handle non-uniformly sampled data
if max(diff(wlog.curves(:,1))) <= step % New step size larger than original one
if isfield(wlog,'null')
no_nan=0;
else
no_nan=1;
end
for ii=2:ncurves
logout.curves(:,ii)=interp_av(wlog.curves(:,1),wlog.curves(:,ii),depth,no_nan);
end
else % New step size is smaller than the original one
for ii=2:ncurves
logout.curves(:,ii)=interp1q(wlog.curves(:,1),wlog.curves(:,ii),depth);
end
end
end
otherwise
error(' Unknown option')
end
% Turn on warnings regarding NaN's in "interp1" that had been turned off before
if S4M.matlab_version >= 7
warning('on','MATLAB:interp1:NaNinY')
end
% Copy rest of fields
logout=copy_fields(wlog,logout);
% Handle logicals (if they exist)
index=find(ismember(lower(wlog.curve_info(:,2)),'logical'));
if ~isempty(index)
temp=logout.curves(:,index);
temp(temp > 0.33 & temp < 0.67)=NaN;
temp=round(temp);
logout.curves(:,index)=temp;
alert({'Interpolation of curves with units "logical" (such as "sand", "shale", etc.)';...
'is not reliable. Such curves should be recomputed.'})
end
% Check for NaNs
if any(any(isnan(logout.curves(:,2:end))))
logout.null=NaN;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function yy=interp_av(x,y,xi,no_nan)
% Function interpolates x,y pairs to new sampling; the interpolation
% is performed in such a way that the output sample for abscissa xi(k)
% is the average of the function y in the interval xi(k-1)+xi(k))/2, (xi(k)+xi(k+1))/2
% yy=interp_av(x,y,xi)
% INPUT
% x,y abscissa and associated ordinate of given function
% xi desired abscissa values
% no_nan logical; no_nan is true if there are no NaNs in y, it is false otherwise
% OUTPUT
% yy interpolated ordinates
if no_nan
u=cumquad(y,x);
xih=[xi(1);(xi(1:end-1)+xi(2:end))/2;xi(end)];
temp=interp1q(x,u,xih);
yy=diff(temp)./diff(xih);
else
idx=find(~isnan(y));
if isempty(idx)
yy=NaN*zeros(size(xi));
return
end
y1=y(idx); x1=x(idx);
u=cumquad(y1,x1);
xih=[xi(1);(xi(1:end-1)+xi(2:end))/2;xi(end)];
temp=interp1q(x1,u,xih);
yy=diff(temp)./diff(xih);
end
|
github
|
Abakumov/MLIB-master
|
write_las_file.m
|
.m
|
MLIB-master/OTHER/SeisLab_10.0301/S4M/Geophysics_3.0/write_las_file.m
| 12,646 |
utf_8
|
d6740bc80ea29cd417d21f55c444ba91
|
function write_las_file(wlog,filename,iprint)
% Function creates a disk file in LAS (Log ASCII Standard)format,
% Version 2.0, as specified by the Canadian Well Logging Society
%
% Written by: E. Rietsch: February 20, 2000
% Last updated: October 10, 2007: Use function "open_file" to handle file initiation
%
% write_las_file(wlog,filename,iprint)
% INPUT
% wlog structure containing the log curves and ancillary information
% Required fields
% wlog.type 'well-log'
% wlog.tag Tag, e.g. 'unspecified'
% wlog.name Name of the log
% wlog.curves Matrix of curve values
% Each log curve is in a c"wlog.curves" has n columns, then there
% are n-1 log curves. The LAS format does not allow exponents in
% the curve values. Hence care should should be taken to ascertain
% that the log values can be represented accurately enough with a
% total no more than 2-3 decimal digits.
% wlog.curve_info Cell array (3 x number of curves) with curve mnemonics,
% curve units of measurement, and curve descriptions
% wlog.null Null value (set to NaN); only required if there are null values
% wlog.first Start of log (first depth in file)
% wlog.last Stop of log (last depth in file)
% wlog.step Depth increment (0 if unequal)
% wlog.units Units of measurement for depth
% wlog.wellname Well name
% wlog.field Name of the field (this could be WILDCAT)
% wlog.location Location of well
% wlog.company Oil/gas company which drilled the well
%
% The following components, while desirable, are either optional
% or are replaced by defaults. They include
% Well information
% wlog.country Country in which well is located
% wlog.wellid Well Identifier
% wlog.service Service company which logged the well
% wlog.province Province
% wlog.county County
% wlog.state State
% wlog.date Date (default: current data)
% wlog.api API number
% wlog.uwi Unique well ID
%
% Parameters which have numerical values other than the null value are
% written to the Parameter Section of the LAS header.
% In the log structure a parameter is represented by a field with
% the parameter name and a row in the cell array "wlog.parameter_info".
% Such a row consists of three strings: the first is the parameter
% mnemonic, the second the units of measurement, and the third the
% parameter description. An example is:
% 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'}
%
%
% filename name of the file; if empty or omitted a file selector box will be opened
% for interactive file selection
%
% iprint print control parameter (iprint = 0, no printout,
% iprint = 1; LAS header is printed, default)
%
% EXAMPLE
% wlog=l_data;
% write_las_file(wlog)
if ~istype(wlog,'well_log');
error(' The first input argument must be a well log.')
end
if nargin <= 3;
iprint=0;
if nargin < 2
filename='';
end
end
line_feed=char(10);
% Replace NaNs (if they exist) by new null value
if isnull(wlog)
wlog.curves(isnan(wlog.curves))=-999.25;
end
wlog.null=-999.25;
% If a 4-decimal representation of wlog.step is not sufficient,
% replace wlog.step by 0
temp=wlog.step*10000;
if temp-fix(temp) > 1.0e-6
wlog.step=0;
end
lasheader=make_las20_header(wlog,line_feed,iprint);
if iprint == 1
disp(lasheader)
end
% Open file for writing
if ~isempty(filename)
fid=open_file('wt',filename);
else
fid=open_file('wt','*.las');
end
fprintf(fid,'%s',lasheader);
% ASCII data
mnems=char(wlog.curve_info{:,1});
[n,m]=size(mnems);
nchar=12; % Number of characters per column
if m < nchar % Append nchar-m blanks to mnemonics
stemp=blanks(nchar-m);
stemp=stemp(ones(n,1),:);
mnems=[mnems,stemp];
else
mnems=mnems(:,1:nchar);
end
lash1=['~A ', reshape(mnems',1,nchar*n),line_feed];
fprintf(fid,'%s',lash1);
if iprint == 1; fprintf('%s',lash1); end
[n,m]=size(wlog.curves);
% Create format for ASCII data (minimum four digits)
% ac=abs(wlog.curves);
textformat=cell(m+1,1);
textformat{end,1}='\n';
for ii=1:m
nd1=ceil(log10(max(abs(wlog.curves(:,ii))+eps)))+2;
nd2=max(10-nd1,0);
if nd1+nd2 < nchar-1
nd1=nchar;
else
nd2=2;
nd1=nd1+4;
end
if ii == 1
if wlog.step == 0 || fix(wlog.step*nd2) ~= wlog.step*nd2
nd2=3;
end
end
textformat{ii}=['%',num2str(nd1),'.',num2str(nd2),'f'];
end
% textformat=[txtformat,'\n'];
textformat=cell2str(textformat,'');
fprintf(fid,textformat,wlog.curves');
if iprint == 1
fprintf('%d of %d lines of curve data written\n',n,n)
end
fclose(fid);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function lash=make_las20_header(wlog,line_feed,iprint)
% Function creates simple header for LAS file
% Date Feb. 19, 2000; written by E. Rietsch
% INPUT
% wlog Log structure
% Required fields
% wlog.curves Matrix of curve values
% Each log is in a column and the first column is usually the depth.
% Thus, if logmat has n columns, then there are n-1 log curves.
% The LAS format does not allow exponents in the curve values.
% Hence care should should be taken to ascertain that the log values
% can be represented accurately enough with a total no more than
% 2-3 decimal digits.
% wlog.mnem Cell array with curve mnemonics
% wlog.units Cell array with curve units of measurement
% wlog.description Cell array with curve description
% wlog.null Null value (set to NaN)
% wlog.first Start of log (first depth in file)
% wlog.last Stop of log (last depth in file)
% wlog.step Depth increment (0 if unequal)
% wlog.wellname Well name
% wlog.field Name of the field (this could be WILDCAT)
% wlog.location Location of well
% wlog.company Oil/gas company which drilled the well
%
% The following components, while desirable, are either optional
% or are replaced by defaults. They include
% Well information
% wlog.country Country in which well is located
% wlog.wellid Well Identifier
% wlog.service Service company which logged the well
% wlog.province Province
% wlog.county County
% wlog.state State
% wlog.date Date
% wlog.api API number
% wlog.uwi Unique well ID
%
% Parameters which have numerical values other than the null value are
% written to the Parameter Section of the LAS header.
% In the log structure a parameters is represented by field with
% the parameter name and a row in the cell array wlog.parameter_info.
% Such a row consists of three strings: the first is the parameter
% mnemonic, the second the units of measurement and the third the
% parameter description.
% wwlog.ekb=84 Kelly bushing elevation
% wwlog.egl=0 Ground level elevation
% wwlog.parameter_info={'ekb','ft','Kelly bushing elevation';
% 'egl','ft','Ground level elevation'}
%
% line_feed line-feed character
% iprint Control diagnostic output (optional)
% iprint = 0 ==> no output; DEFAULT
% iprint ~= 0 ==> diagnostic output
% OUTPUT
% lash LAS header
%
% lash=make_las20_header(wlog,line_feed,iprint)
if nargin == 2, iprint=0; end
% Version information section
lash=['~VERSION INFORMATION SECTION',line_feed, ...
'VERS. 2.0 :CWLS Log ASCII Standard - 2.0',line_feed, ...
'WRAP. NO :One line per depth',line_feed, ...
'# Created in SeisLab',line_feed];
if iprint == 1, fprintf('... start well information section\n'), end
% Well information section
stemp=wlog.curve_info{1,2};
start=['STRT.',stemp,' ',num2str(wlog.first)];
stop=['STOP.',stemp,' ',num2str(wlog.last)];
step=['STEP.',stemp,' ',num2str(wlog.step)];
null=['NULL. ',num2str(wlog.null)];
lash1=char('#MNEM.UNIT VALUE/NAME',start,stop,step,null);
lash2=char(' :DESCRIPTION',' :Start Depth',' :Stop Depth',' :Step', ...
' :Null Value');
if isfield(wlog,'wellname')
lash1=char(lash1,['WELL. ',wlog.wellname]);
else
lash1=char(lash1,['WELL. ','UNKNOWN']);
end
lash2=char(lash2,' :Well Name');
if isfield(wlog,'country'),
lash1=char(lash1,['CTRY. ',wlog.country]);
else
lash1=char(lash1,['CTRY. ','UNKNOWN']);
end
lash2=char(lash2,' :Country');
if isfield(wlog,'county'),
lash1=char(lash1,['CNTY. ',wlog.county]);
else
lash1=char(lash1,['CNTY. ','UNKNOWN']);
end
lash2=char(lash2,' :County');
if isfield(wlog,'state'),
lash1=char(lash1,['STAT. ',wlog.state]);
else
lash1=char(lash1,['STAT. ','UNKNOWN']);
end
lash2=char(lash2,' :State');
if isfield(wlog,'api'),
lash1=char(lash1,['API . ',wlog.api]);
else
lash1=char(lash1,['API . ','UNKNOWN']);
end
lash2=char(lash2,' :API number');
if isfield(wlog,'uwi'),
lash1=char(lash1,['UWI . ',wlog.uwi]);
else
lash1=char(lash1,['UWI . ','UNKNOWN']);
end
lash2=char(lash2,' :Unique well ID');
if isfield(wlog,'location'),
lash1=char(lash1,['LOC . ',wlog.location]);
else
lash1=char(lash1,['LOC . ','UNKNOWN']);
end
lash2=char(lash2,' :Well Location');
if isfield(wlog,'field'),
lash1=char(lash1,['FLD . ',wlog.field]);
else
lash1=char(lash1,['FLD . ','UNKNOWN']);
end
lash2=char(lash2,' :Field');
if isfield(wlog,'company'),
lash1=char(lash1,['COMP. ',wlog.company]);
else
lash1=char(lash1,['COMP. ','UNKNOWN']);
end
lash2=char(lash2,' :Company');
if isfield(wlog,'service'),
lash1=char(lash1,['SRVC. ',wlog.service]);
else
lash1=char(lash1,['SRVC. ','UNKNOWN']);
end
lash2=char(lash2,' :Service Company');
if isfield(wlog,'date'),
lash1=char(lash1,['DATE. ',wlog.date]);
else
lash1=char(lash1,['DATE. ',date]);
end
lash2=char(lash2,' :Date');
lash=[lash,'~WELL INFORMATION SECTION',line_feed];
for ii=1:size(lash1,1)
lash=[lash,lash1(ii,:),lash2(ii,:),line_feed]; %#ok
end
if iprint == 1, fprintf('... completed well information section\n'), end
% Parameter information section (parameters are fields of the log structure
% which matching entry in the first column of the cell array
% wlog.parameter_info
if ~isfield(wlog,'parameter_info')
np=0;
else
parameters=wlog.parameter_info(:,1);
np=length(parameters);
end
temps1='#MNEM';
temps1a='.UNITS';
temps2=' VALUE';
temps3=' :DESCRIPTION OF PARAMETER';
for ii=1:np
temps=wlog.parameter_info(ii,2:3);
temps1=char(temps1,parameters{ii});
temps1a=char(temps1a,['.',temps{1}]);
% temps2=char(temps2,[' ',num2str(getfield(wlog,parameters{ii}))]);
temps2=char(temps2,[' ',num2str(wlog.(parameters{ii}))]);
temps3=char(temps3,[' :',temps{2}]);
end
lash=[lash,'~PARAMETER INFORMATION SECTION',line_feed];
for ii=1:size(temps1,1)
lash=[lash,temps1(ii,:),temps1a(ii,:),temps2(ii,:),temps3(ii,:),line_feed]; %#ok
end
if iprint == 1
fprintf('... completed parameter information section\n')
end
% Curve information section
if iprint == 1
fprintf('... start curve information section\n')
end
ncurves=size(wlog.curves,2);
temps1='#MNEM';
temps1a='.UNITS';
temps1b=' API CODES';
temps2=' :DESCRIPTION OF MNEMONIC';
for ii=1:ncurves
temps1=char(temps1,wlog.curve_info{ii,1});
temps1a=char(temps1a,['.',wlog.curve_info{ii,2}]);
temps1b=char(temps1b,' ');
temps2=char(temps2,[' :',wlog.curve_info{ii,3}]);
end
% lash=char(lash,'~CURVE INFORMATION SECTION',[temps1,temps2]);
lash=[lash,'~CURVE INFORMATION SECTION',line_feed];
for ii=1:size(temps1,1)
lash=[lash,temps1(ii,:),temps1a(ii,:),temps1b(ii,:),temps2(ii,:),line_feed]; %#ok
end
if iprint == 1, fprintf('... completed curve information section\n'), end
% Other information
if isfield(wlog,'comments')
% lash=char(lash,'~Other information',wlog.comments);
lash=[lash,'~Other information',wlog.comments,line_feed];
end
|
github
|
Abakumov/MLIB-master
|
s_history.m
|
.m
|
MLIB-master/OTHER/SeisLab_10.0301/S4M/Geophysics_3.0/s_history.m
| 4,674 |
utf_8
|
505210de012d4898b0687b47b8394b4b
|
function seismic=s_history(seismic,action,parameters)
% Function operates on the history field of a seismic structure; displays data set history
% if no output argument is given
%
% Written by: E. Rietsch: March, 2001
% Last updated: November 29, 2006: handle structure vectors
%
% seismic=s_history(seismic,action,parameters)
% INPUT
% seismic seismic structure or structure vector whose history field(s)
% needs to be created, modified, ...
% action string describing the action to take; possible values are:
% 'add' Add a history field to the seismic structure
% 'append' Append new information about the present command
% to seismic.history (if it exists)
% 'merge' Append history field from another seismic structure
% 'delete' Delete the last cell of seismic.history
% (if the history field exists; not yet implemented)
% 'list' List seismic.history (default if no action specified)
% parameters for 'add' and 'append': character string to be posted in history field;
% for 'merge': history field of a seismic structure
% OUTPUT
% seismic seismic structure whose history field has been created/appended
%
%
% EXAMPLE
% seismic=s_data;
% s_history(seismic)
global S4M
if ~S4M.history || isempty(S4M.start_time)
return
end
if nargin == 1
action='list';
end
if ~isfield(seismic(1),'history') && ~strcmpi(action,'add')
return
end
if ~strcmp(action,'list')
% Find level and name of the calling program; return to calling program if
% level is too deep.
temp=dbstack;
if length(temp) < 2 % Return if not called by function
return
end
level=size(temp,1)-1;
if isempty(S4M.start_level)
S4M.start_level=level;
level_difference=0;
else
level_difference=level-S4M.start_level;
if level_difference > S4M.history_level
return
elseif level_difference < 0
level_difference=0;
end
end
[dummy,filename] = fileparts(temp(2).name); %#ok First output argument is not required
program=upper(filename);
else
level_difference=0; % Dummy variable
program=''; % Dummy variable
end
if nargin < 3
parameters=[];
end
if strcmpi(action,'add')
[seismic.history]=deal([]);
end
for ii=1:length(seismic)
[seismic(ii),terminate]=act_on_history_request(seismic(ii),action, ...
parameters,level_difference,program);
if terminate
break
end
end
if nargout == 0
if ~strcmpi(action,'list')
display_seismic_history(seismic(1))
end
clear seismic
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function display_seismic_history(seismic)
spaces=blanks(size(seismic.history,1)+1)';
% commas=char(44*ones(size(seismic.history,1)+1,1));
history=[char('Day/Time of Program Start',char(seismic.history(:,1))),spaces,...
char(' TiP',num2str(cat(1,seismic.history{:,2}))), spaces, ...
char('Program',char(seismic.history(:,3))),spaces, ...
char('Parameters',char(seismic.history{:,4}))];
disp(history)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [seismic,terminate]=act_on_history_request(seismic,action, ...
parameters,level_difference,program)
global S4M
terminate=false;
switch action
case 'add'
if isempty(S4M.start_time)
S4M.start_time=clock; % Date and time as 6-elemenmt array
end
if isempty(S4M.time)
S4M.time=datum; % Date and time as string
end
if S4M.history
t=clock-S4M.start_time;
seismic.history={[blanks(level_difference),S4M.time, ...
blanks(S4M.history_level-level_difference)], ...
round(((24*t(3)+t(4))*60+t(5))*60+t(6)),program,parameters};
end
case 'append'
t=clock-S4M.start_time;
seismic.history=[seismic.history;{[blanks(level_difference),S4M.time, ...
blanks(S4M.history_level-level_difference)], ...
round(((24*t(3)+t(4))*60+t(5))*60+t(6)),program,parameters}];
case 'merge'
merge=parameters;
m=size(merge,1);
prefix='<< ';
for ii=1:m
seismic.history=[seismic.history; ...
{[prefix,merge{ii,1}],merge{ii,2},merge{ii,3},merge{ii,4}}];
end
case 'list'
terminate=true;
if ~isfield(seismic(1),'history')
disp(' Input data set has no history field.')
clear seismic;
return
end
display_seismic_history(seismic(1))
otherwise
error(['Action "',action,'" unknown or not yet implemented.'])
end
|
github
|
Abakumov/MLIB-master
|
s_principal_components.m
|
.m
|
MLIB-master/OTHER/SeisLab_10.0301/S4M/Geophysics_3.0/s_principal_components.m
| 9,184 |
utf_8
|
45ea0d6d1a65fda0f2d42cb5b619108e
|
function [pc,aux]=s_principal_components(seismic,varargin)
% Perform principal-component analysis of the input dataset.
% The output can be:
% A. The input data represented by any combination of the principal
% components --- usually the first few: {'output','seismic'}
% B. One or more of the principal components in form of a seismic data set.
% The first trace is the first requested principal component, etc.
% {'output','pc'}
% C. The coefficients of the principal components for each trace
% {'output','coefficients'}
%
% Written by: E. Rietsch: July 18, 2000
% Last updated: September 20, 2009: General streamlining
%
% [pc,aux]=s_principal_components(seismic,varargin)
% INPUT
% seismic seismic data set
% varargin one or more cell arrays; the first element of each cell array is
% a keyword, the other elements are parameters. Presently, keywords are:
% 'output' Type of output. Possible values are:
% 'pc' (principal components), 'seismic', 'coefficients'.
% In the first case one trace is output for each principal
% component requested; headers which are constant are output as well.
% In the second case the number of output traces equals the number
% of input traces and all headers are copied.
% In the third case the coefficients of the principal components for
% each trace are output. Again the number of output traces is the
% same as the number of input traces.
% Default: {'output','seismic'}
% 'index' Index/indices of the principal components requested.
% Possible values are integers > 0.
% The maximum value, "maximum_value", is the smaller of the number of
% samples per trace and the number of traces. A request for principal
% components with higher index is ignored.
% Default: if {'output','seismic'} then {'index',1}
% if {'output','pc'} then {'index',1:maximum_value}
% OUTPUT
% pc seismic structure;
% if {'output','seismic'} it is the seismic input dataset
% represented by the principal components requested via keyword
% 'index'.
% if {'output','pc'} it is set of principal components requested
% via keyword 'index'.
% aux structure with auxiliary information
% if output is "seismic'
% 'energy' row vector: scaled energy of the principal components of
% each trace; these numbers represent the fraction of the total
% trace energy represented by that specific combination of
% principal components.
% 'd' row vector: cumulative sum of the squared singular values
% (scaled so that the last entry is 1). It is the fraction
% of the total energy of the seismic dataset represented
% by the principal components as the number of principal
% components used is increased.
%
% if output is "pc"
% 'sing_values' singular values associated with the requested principal
% components (normalized so that the sum of the squares of all
% singular values is 1)
%
% EXAMPLES
% seismic=s_data;
%
% [pc,aux]=s_principal_components(seismic);
% disp(aux)
%
% s_wplot(pc)
% mytitle('First principal component of each trace (correctly scaled)')
%
% % Consistency test
% comp=s_principal_components(seismic,{'output','pc'});
% coeff=s_principal_components(seismic,{'output','coefficients'});
%
% test=s_convert(comp.traces*coeff.traces,0,seismic.step);
%
% s_compare(seismic,test);
% mytitle('Comparison of original traces (black) and reconstituted traces (red)')
% UPDATE HISTORY
% October 17, 2006: "components" option of keyword "output" redone;
% no polarity change for principal components
%
if ~istype(seismic,'seismic')
error(' First input argument must be a seismic dataset.')
end
if isnull(seismic)
error(' Seismic data must not contain NaNs')
end
pc=seismic;
[nsamp,ntr]=size(seismic.traces);
min_nsamp_ntr=min([nsamp,ntr]);
%% Set default values of optional input arguments
param.output='seismic';
param.index=[];
% Replace defaults by actual input arguments
param=assign_input(param,varargin);
% Set/check number of principal components requested.
if isempty(param.index)
if strcmpi(param.output,'seismic')
param.index=1;
else
param.index=1:min_nsamp_ntr;
end
else
param.index=param.index(param.index <= min_nsamp_ntr);
end
%% Switch to the requested output option
switch param.output
case 'seismic'
[pr_cmp,energy,d]=princ_comp_no1(seismic.traces,param.index);
pc.traces=pr_cmp;
% Add history field if it exists in seismic
aux.energy=energy;
aux.d=d';
pc=ds_header(pc,'add_ne','energy',energy,'n/a','Fraction of total trace energy retained');
case 'pc'
[pc.traces,sing_val]=princ_comp_no2(seismic.traces,param.index);
pc.name='Principal components';
% Copy headers that are constant and delete others
if isfield(seismic,'header_info')
nh=size(seismic.headers,1);
headers=zeros(nh,size(pc.traces,2));
header_info=cell(nh,3);
icount=0;
for ii=1:nh
if min(seismic.headers(ii,:)) == max(seismic.headers(ii,:))
icount=icount+1;
headers(icount,:)=seismic.headers(ii,1);
header_info(icount,:)=seismic.header_info(ii,:);
end
end
if icount > 0
pc.headers=headers(1:icount,:);
pc.header_info=header_info(1:icount,:);
else
pc=rmfield(pc,{'headers','header_info'});
end
end
if nargout > 1
aux.sing_values=sing_val;
end
case 'coefficients'
[pc.traces,d]=princ_comp_no3(seismic.traces,param.index);
if nargout > 1
aux.sing_values=d;
end
pc.first=1;
pc.last=length(param.index);
pc.step=1;
pc.units='Index';
pc.tag='principal_components';
pc.row_label=param.index(:);
pc.name='Coefficients of the principal components';
% aux.d=d
otherwise
error([' Unknowm option for keyword "output": ',param.output])
end % End of switch block
% Add entry to the history field if it exists in seismic
htext=[' Principal components: ',num2str(param.index)];
pc=s_history(pc,'append',htext);
%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [pc,energy,dd]=princ_comp_no1(s,npc)
% Function computes principal components of matrix s over the range npc and
% outputs them together with the total relative energy in each column of s.
%
% [pc,energy,d]=princ_comp_no1(s,npc)
% INPUT
% s input matrix
% npc row vector with the indices of the principal components to use
% max(npc) <= number of columns of s
% OUTPUT
% pc principal components
% energy fraction of total trace energy
[ns,ntr]=size(s);
% Perform singular-value decomposition
if ns >= ntr
[u,d,v]=svd(s,0);
else
[v,d,u]=svd(s',0);
end
% Store singular values in a vector and compute normalization factor
% so that the sum of their squares is 1
d=diag(d);
if nargout > 2;
dd=d.^2;
scf=1/sum(dd);
dd=cumsum(dd)*scf;
else
scf=1/sum(d.^2);
end
% Compute the coefficients of the requested principal components for
% each column of the matrix
ik=0;
vv=zeros(size(v,1),length(npc));
for ii=npc
ik=ik+1;
vv(:,ik)=v(:,ii)*d(ii);
end
% Select the requested principal components
pc=u(:,npc)*vv';
if ik == 1
energy=reshape((vv.^2)*scf,1,[]);
else
energy=sum(vv.^2,2)'*scf;
end
% Normalize energy on a trace-by-trace basis
trace_energy=sum(s.^2);
scf1=sum(trace_energy)./trace_energy;
energy=energy.*scf1;
%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [pc,sing_val]=princ_comp_no2(s,npc)
% Function computes principal components of s over the range of indices npc
% and outputs them together with the total relative energy in each column of s.
%
% [pc,sing_val]=princ_comp1(s,npc)
% INPUT
% s input array
% npc indices of principal components to use
% OUTPUT
% pc principal components
% sing_val normalized singular values (sum of squares = 1)
[u,dd]=svd(s,0);
d=diag(dd);
pc=u(:,npc);
sing_val=d(npc)./sqrt(sum(d.^2));
%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [vv,dd]=princ_comp_no3(s,npc)
% Function computes coefficients of the principal components of s over
% the range of indices npc and outputs them together with the total
% relative energy in each column of s.
%
% [pc,sing_val]=princ_comp1(s,npc)
% INPUT
% s input array
% npc indices of principal components to use
% OUTPUT
% vv Matrix with coefficients of the principal components for each column of s
% there are as many columns as there are columns of "s"
% d all singular values
[dummy,d,v]=svd(s,0); %#ok
dd=diag(d)';
vv=zeros(length(npc),size(s,2));
ik=0;
for ii=npc
ik=ik+1;
vv(ik,:)=v(:,ii)'*dd(ii);
end
|
github
|
Abakumov/MLIB-master
|
showcell.m
|
.m
|
MLIB-master/OTHER/SeisLab_10.0301/S4M/Geophysics_3.0/showcell.m
| 15,708 |
utf_8
|
081f227ddee7a4c67b9b8afd95b4f5c7
|
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
|
s_align.m
|
.m
|
MLIB-master/OTHER/SeisLab_10.0301/S4M/Geophysics_3.0/s_align.m
| 14,853 |
utf_8
|
60bcd8ccf2428d666af347c69c483aeb
|
function seismic=s_align(seismic,varargin)
% Function aligns (flattens) a user-specified event on seismic traces.
% The shifts required for alignment as well as the correlation coefficient can
% be stored in headers.
%
% Written by: E. Rietsch: February 19, 2001
% Last updated: February 13, 2008: Use "isnull" to check for trace nulls
%
% seismic=s_align(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:
% 'reference' Reference trace in terms of a header mnemonic
% General form: {'reference',mnem,value}
% "mnem" denotes a string with a header mnemonic ('trace_no' is
% permissible even if there are no headers). "value" is the value of
% the header mnemonic. An error message is printed if the header
% mnemonic does not exist or if there is no trace or more than one
% trace with this value.
% Default: {'reference','trace_no',1}
% 'window' Start time and end time of a window on the reference trace;
% the other traces are aligned to the signal in this window.
% General form: {'window',ta,te}; seismic.first < ta < te < seismic.last
% Default: {'window',seismic.first,seismic.last}
% 'maxshift' Maximum shift (ms) allowed in either direction. It should be
% chosen big enough to include all possible shifts between the
% reference signal on the reference trace and the corresponding
% signal on any other trace. See also keyword 'adapt' below.
% Default: {'maxshift',0.5*seismic.last-seismic.first)}
% 'adapt' String variable specifying if the window should remain fixed
% (adapt='no') or move with the event (adapt='yes'). If the shifts
% have a "trend" the maxshift value can be chosen to equal the
% maximum trace-to-trace shift which then could be fairly small.
% Default: {'adapt','yes'} unless 'maxshift' is not defined.
% 'shifts' Header mnemonic to use to store the shifts that were applied
% to the traces. General form: {'shifts',mnemonic}
% Shifts are not stored if "mnemonic" is an empty string
% Default: {'shifts','align_shifts'}
% 'correlations' Header mnemonic used to store correlation coefficients.
% General form: {'correlation',mnemonic}
% Correlation coefficients are not stored if "mnemonic" is
% an empty string
% Default: {'correlation','align_corr'}
% 'method' Method used to establish maximum similarity.
% Method 1: Normalized cross-correlation
% method 2: Crosscorrelation without trace-segment normalization
% Default: {'method',2}
% 'update' numerical factor specifying if the reference signal is to be
% the signal updated to account for systematic column-to-column
% changes in (e.g. NMO stretch).
% "update" must satisfy 0 <= update <= 1.
% new_reference_signal=(1-update)*old_reference_signal +
% update*signal_on_last_trace
% Default: {'update',0} (i.e. reference signal is not updated)
% 'option' this keyword determines what should be done with data that
% are shifted outside the time range of seismic. Options are:
% 'extend' extend the time range to accommodate all shifts.
% This is the default. It means that
% seismic.first+min(shifts) ==> seismic.first
% seismic.last+max(shifts) ==> seismic.last
% '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 "seismic". This will happen whenever different traces are
% shifted by different amounts AND 'type' is not 'circular'.
% Default: {'null',0}.
% If the null field of the input dataset is empty and null=0, then the
% null field of the output dataset will also be empty.
%
% OUTPUT
% seismic seismic structure with shifts applied; unless specified otherwise,
% shifts and correlation coefficients are stored in headers.
%
% EXAMPLE
% % Create test data
% wavelet=s_create_wavelet({'step',1});
% wavelets=s_select(wavelet,{'traces',ones(1,11)});
% wavelets=s_shift(wavelets,{'shifts',[0:10].^2});
% wavelets.name='Original wavelets';
%
% % Align shifted wavelets
% aligned_wavelets=s_align(wavelets,{'adapt','yes'},{'null',NaN});
%
% % Display test data and the result of the alignment
% lfigure
% subplot(1,2,1)
% s_wplot(wavelets,{'figure','old'},{'times',-150,150})
% subplot(1,2,2)
% s_wplot(aligned_wavelets,{'figure','old'},{'times',-150,150})
% disp(' Shifts that were applied:')
% disp(ds_gh(aligned_wavelets,'align_shifts'))
% UPDATE HISTORY
% April 3, 2006: Add all header mnemonics with the "add_ne" option
if ~istype(seismic,'seismic')
error(' First input argument must be a seismic dataset.')
end
% Set default values for input arguments
param.adapt='yes';
param.correlations='align_corr';
param.maxshift=[];
param.null=0;
param.reference={'trace_no',1};
param.option='extend';
param.shifts='align_shifts';
param.method=2;
param.update=0;
param.window={seismic.first,seismic.last};
% Replave defaults by actual input arguments
param=assign_input(param,varargin,'s_align');
method=param.method;
ntr=size(seismic.traces,2);
if ntr == 1
if ~isempty(param.shifts)
seismic=ds_header(seismic,'add_ne',param.shifts,0,seismic.units, ...
'Time shifts applied to traces in param');
end
if ~isempty(param.correlations)
seismic=ds_header(seismic,'add_ne',param.correlations,1,'n/a', ...
'Coefficient of correlation with reference signal');
end
return
end
if isempty(param.window)
error(' Window containing event must be specified')
else
if iscell(param.window)
param.window=cell2num(param.window);
end
ita=round((param.window(1)-seismic.first)/seismic.step);
ite=round((param.window(2)-seismic.first)/seismic.step);
ta=ita*seismic.step+seismic.first;
te=ite*seismic.step+seismic.first;
if find(diff([seismic.first;ta;te;seismic.last]) < 0)
error([' Window (',num2str([ta,te]),') is not within range of seismic data (', ...
num2str([seismic.first,seismic.last]),').'])
end
end
if isempty(param.maxshift)
param.maxshift=round(0.5*(seismic.last-seismic.first)/seismic.step);
param.adapt='no';
else
param.maxshift=round(param.maxshift/seismic.step);
end
if ~iscell(param.reference) % Substitute default header if none is given
param.reference={'trace_no',param.reference};
end
itrace=param.reference{2};
if strcmpi(param.reference{1},'trace_no')
if itrace < 1 || itrace > ntr
error([' Reference trace (',num2str(itrace),') outside range of traces (1-', ...
num2str(ntr),') available'])
end
else
headers=s_gh(seismic,param.reference{1});
itrace=find(ismember(headers,itrace));
if length(itrace) > 1
error([' More than one header "',param.reference{1},'" with value ',num2str(param.reference{2})])
elseif isempty(itrace)
error([' No header "',param.reference{1},'" with value ',num2str(param.reference{2})])
else
% Everything is OK
end
end
% Compute lags
if isnull(seismic)
temp=seismic.traces;
% index=find(isnan(temp));
temp(isnan(temp))=0;
disp(' Alert from "s_align": Null values in data set replaced by zeros')
if strcmpi(param.adapt,'yes')
[lags,cc]=trace_align_adapt(temp,itrace,ita+1,ite+1, ...
param.maxshift,param.update,method);
else
[lags,cc]=trace_align_noadapt(temp,itrace,ita+1,ite+1, ...
param.maxshift,param.update,method);
end
else
if strcmpi(param.adapt,'yes')
[lags,cc]=trace_align_adapt(seismic.traces,itrace,ita+1,ite+1, ...
param.maxshift,param.update,method);
else
[lags,cc]=trace_align_noadapt(seismic.traces,itrace,ita+1,ite+1, ...
param.maxshift,param.update,method);
end
end
shifts=lags*seismic.step;
% Shift input traces
if ~all(shifts==0)
name=seismic.name;
seismic=s_shift(seismic,{'shifts',shifts},{'option',param.option},{'null',param.null});
seismic.name=[name,' (aligned)'];
end
% Store crosscorrelations in header
if ~isempty(param.correlations)
seismic=ds_header(seismic,'add_ne',param.correlations,cc,'n/a', ...
'Coefficient of correlation with reference signal');
end
% Store shifts in header
if ~isempty(param.shifts)
seismic=ds_header(seismic,'add_ne',param.shifts,shifts,'ms', ...
'Time shifts applied to traces');
end
% Append history field
if isfield(seismic,'history')
htext=[ 'adapt: ',param.adapt,', update: ',num2str(param.update),', option: ',param.option];
seismic=s_history(seismic,'append',htext);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [lag,cc]=trace_align_adapt(a,itr,ia,ie,maxshift,update,method)
% Function aligns a "signal" in columns of matrix "a" with the signal in a
% reference column.
% It outputs the shifts required for alignment with this reference signal
% and the coefficient of correlation.
% [lag,cc]=align(a,itr,ia,ie,maxshift,update,method)
% INPUT
% a matrix whose columns are to be aligned
% itr index of column to use as reference for alignment
% ia index of first row to use for the signal in the reference column
% ie index of last row to use for the signal in the reference column
% maxshift maximum shift (up or down) allowed
% update numerical factor specifying if the reference signal is to be updated to account
% for systematic column-to-column changes in the signal (e.g. NMO stretch).
% "update" must satisfy 0 <= update <= 1.
% new_reference_signal=(1-update)*old_reference_signal + update*signal_on_last_trace
% method option regarding measurement of similarity
% OUTPUT
% lag shifts found (of course, lag(itr)=0). Positive values of the lag
% mean a shift down, negative values a shift up.
% cc crosscorrelation between the reference signal and the signal
% on each trace. (Of course, cc(itr)=1).
[nsamp,ntr]=size(a);
ref=a(ia:1:ie,itr);
nref=length(ref);
%index=zeros(ntr,1);
iai=ia; % Initialize start of search window
iei=ie;
lag=zeros(ntr,1);
cc=ones(ntr,1);
refi=ref;
for ii=itr-1:-1:1
minshift=-min([maxshift,iai-1]);
iae=iai+minshift;
aa=a(iae:min([iei+maxshift,nsamp]),ii);
if method == 1
[cci,lagi]=cornor(aa,refi,'max');
else
[lagi,cci]=max_corr(aa,refi,0,-minshift+maxshift);
end
lag(ii)=lag(ii+1)-lagi-minshift;
cc(ii)=cci;
iai=ia-lag(ii); % Update start of search window
iei=ie-lag(ii);
% Update reference signal
if lagi >= 0
tie=iae+lagi+nref-1;
if tie > nsamp
refi=refi*(1-update)+[update*a(iae+lagi:nsamp,ii);zeros(tie-nsamp,1)];
else
refi=refi*(1-update)+update*a(iae+lagi:tie,ii);
end
else
refi=refi+[zeros(1-lagi,1);update*aa(1:nref+lagi-1)];
end
end
iai=ia; % Initialize start of search window
iei=ie;
refi=ref;
for ii=itr+1:ntr
minshift=-min([maxshift,iai-1]);
iae=iai+minshift;
aa=a(iae:min([iei+maxshift,nsamp]),ii);
if method == 1
[cci,lagi]=cornor(aa,refi,'max');
else
[lagi,cci]=max_corr(aa,refi,0,-minshift+maxshift);
end
lag(ii)=lag(ii-1)-lagi-minshift;
cc(ii)=cci;
iai=ia-lag(ii); % Update start of search window
iei=ie-lag(ii);
% Update reference signal
if lagi >= 0
tie=iae+lagi+nref-1;
if tie > nsamp
refi=refi*(1-update)+[update*a(iae+lagi:nsamp,ii);zeros(tie-nsamp,1)];
else
refi=refi*(1-update)+update*a(iae+lagi:tie,ii);
end
else
nref=nref+lagi;
% refi=refi(1-lagi:end)+update*aa(1:nref);
refi=refi+[zeros(1-lagi,1);update*aa(1:nref+lagi-1)];
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [lag,cc]=trace_align_noadapt(a,itr,ia,ie,maxshift,update,method)
% Function aligns a "signal" in columns of matrix "a" with the signal in a
% reference column.
% It outputs the shifts required for alignment with this reference signal
% and the coefficient of correlation.
% INPUT
% a matrix whose columns are to be aligned
% itr index of column to use as reference for alignment
% ia index of first row to use for the signal in the reference column
% ie index of last row to use for the signal in the reference column
% maxshift maximum shift (up or down) allowed
% update numerical factor specifying if the reference signal is to be updated to
% account for systematic column-to-column changes in the signal .
% (e.g. NMO stretch) "update" must satisfy 0 <= update <= 1.
% new_reference_signal=(1-update)*old_reference_signal
% +update*signal_on_last_trace
% method option regarding measurement of similarity
% OUTPUT
% lag shifts found (of course, lag(itr)=0). Positive values of the lag mean a shift
% down, negative values a shift up.
% cc crosscorrelation between the reference signal and the signal on each trace.
% (Of course, cc(itr)=1).
% [lag,cc]=align(a,itr,ia,ie,maxshift,adapt,update)
[nsamp,ntr]=size(a);
ref=a(ia:1:ie,itr);
nref=length(ref);
minshift=-min([maxshift,ia-1]);
%iae=max([ia-maxshift,1]);
iae=ia+minshift;
aa=a(iae:min([ie+maxshift,nsamp]),:);
lag=zeros(ntr,1);
cc=ones(ntr,1);
refi=ref;
for ii=itr-1:-1:1
if method == 1
[cci,lagi]=cornor(aa(:,ii),refi,'max');
else
[lagi,cci]=max_corr(aa(:,ii),refi,0,maxshift-minshift);
end
lag(ii)=-lagi-minshift;
cc(ii)=cci;
ia1=max(ia-lag(ii),1);
ia1=min(nsamp-nref+1,ia1);
refi=(1-update)*refi+update*a(ia1:ia1+nref-1,ii);
end
refi=ref;
for ii=itr+1:ntr
if method == 1
[cci,lagi]=cornor(aa(:,ii),refi,'max');
else
[lagi,cci]=max_corr(aa(:,ii),refi,-2*maxshift,2*maxshift);
end
lag(ii)=-lagi-minshift;
cc(ii)=cci;
ia1=max(ia-lag(ii),1);
ia1=min(nsamp-nref+1,ia1);
refi=(1-update)*refi+update*a(ia1:ia1+nref-1,ii);
end
|
github
|
Abakumov/MLIB-master
|
show.m
|
.m
|
MLIB-master/OTHER/SeisLab_10.0301/S4M/Geophysics_3.0/show.m
| 1,134 |
utf_8
|
968e65cbcf04f96c97d46e13ea628057
|
function show(var)
% Function displays numeric variables, structures, and cell arrays in a
% more general form than provided by Matlab and uses "disp" for all other
% variables
%
% Written by: E. Rietsch: January 22, 2006
% Last updated: March 6, 2006: cosmetics
%
% show(var)
% INPUT
% var variable to display in the command window
disp(inputname(1))
if all(isnumeric(var)) && ~all(ishandle(var))
show_no1(var)
elseif isstruct(var)
disp(orderfields(var))
elseif iscell(var)
var1.var=var; % This fancy footwork is designed to prevent the
% name "var" to show up in the list
showcell(var1(1).var)
elseif isobject(var)
display(var)
else
disp(var)
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function []=show_no1(array)
% Function displays 1-D array
% show_no1(array)
% n=length(array);
% scale=10^ceil(log10(max(abs(array))));
scale=1;
fprintf('%7.5g %7.5g %7.5g %7.5g %7.5g %7.5g %7.5g %7.5g %7.5g %7.5g\n',array/scale)
if rem(length(array),10) ~= 0,
fprintf('\n');
end
|
github
|
Abakumov/MLIB-master
|
s_fft.m
|
.m
|
MLIB-master/OTHER/SeisLab_10.0301/S4M/Geophysics_3.0/s_fft.m
| 5,226 |
utf_8
|
5f1dea75a6d1eedc2f1c8c61d18c4af1
|
function ftseismic=s_fft(seismic,varargin)
% Compute the amplitude spectrum or the Fourier transform
% of the traces of the seismic input data set(s).
% The phase is corrected so that the Fourier transform honors time zero; this
% means that a seismic trace symmetric about time zero will have a real
% Fourier transform; analogously, a trace anti-symmetric about time zero will have
% an imaginary Fourier transform (assuming no rounding errors).
%
% See also: s_edft
%
% Written by: E. Rietsch: February 19, 2001
% Last updated: November 30, 2007: modify frequency sample interval if it
% was chosen too large; bug fix
%
% ftseismic=s_fft(seismic,varargin)
% INPUT
% seismic seismic dataset or dataset array
% varargin one or more cell arrays; the first element of each cell array is a
% keyword, the other elements are parameters. Presently, keywords are:
% 'output' type of output. Possible values are:
% 'amp' amplitude spectrum (absolute value of Fourier transform)
% 'ft' Fourier transform (complex)
% Default: {'output','amp'}
% 'df' sample interval in the frequency domain (achieved by padding)
% only used if it is less than the sample interval computed as:
% 1000/(seismic.last-seismic.first+seismic.step).
% This sample interval is also used if {'df',[]}.
% If one wants to define the number of frequency samples, "nfft",
% then "df" needs to be set to
% df=1000/(step*nfft) where step is the sample interval in time;
% alternatively: set {'df',-nfft} and have "df" computed internally
% from "nfft".
% Default: {'df',2}
% OUTPUT
% ftseismic Amplitude spectrum or Fourier transform of traces of
% seismic input data
%
% EXAMPLE
% seismic=s_data;
% ftseismic=s_fft(seismic,{'output','ft'});
% s_compare(real(ftseismic),imag(ftseismic),{'times',0,60})
% mytitle('Real part (black) and imaginary part (red) of FT of seismic data')
% UPDATE HISTORY
% April 17, 2007: modify Fourier transform to honor time zero
if ~istype(seismic,'seismic')
if isnumeric(seismic)
if size(seismic,1) > 1
seismic=s_convert(seismic,1,1,[],'samples');
else
error('The first input argument must be a seismic dataset or a matrix with more than one row.')
end
else
error('The first input argument must be a seismic dataset or a matrix.')
end
end
% Check if the seismic traces are real
for ii=1:length(seismic)
if ~isreal(seismic(ii).traces)
error('Traces of seismic dataset are assumed to be real.')
end
end
% Set default parameters
param.output='amp';
param.df=2;
param.window=[];
% Decode input arguments
param=assign_input(param,varargin);
if ~isempty(param.df)
if param.df < 0
param.df=-1000/(seismic.step*param.df);
end
df0=1000/max([seismic.last]-[seismic.first]+[seismic.step]);
if param.df > df0
param.df=df0;
end
end
for ii=length(seismic):-1:1
ftseismic(ii)=fft_no1(seismic(ii),param); %#ok "ftseismic" is not growing
% since it is computed from the highest index down
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function ftseismic=fft_no1(seismic,param)
% Perform the actual FFT
if isnull(seismic)
seismic=s_rm_trace_nulls(seismic);
end
nsamp=size(seismic.traces,1);
nyquist=500/seismic.step;
if ~isempty(param.df) && param.df > 0
nfft=2*nyquist/param.df;
else
nfft=nsamp;
end
freq=(0:2:nfft)*nyquist/nfft;
ftseismic=seismic;
ftseismic.first=0;
ftseismic.last=freq(end);
ftseismic.step=freq(2);
ftseismic.units=units2frequencydomain(seismic.units);
if isempty(param.window)
temp=seismic.traces;
else
try
wndw=mywindow(nsamp,param.window);
temp=zeros(nsamp,ntr);
for ii=1:ntr
temp(:,ii)=seismic.traces(:,ii).*wndw;
end
catch
temp=seismic.traces;
alert(['Window "',param.window,'" could not be applied'])
end
end
% Number of samples in the frequency domain
nsamp=round(ftseismic.last/ftseismic.step)+1;
ftseismic.traces=fft(temp,nfft);
ftseismic.traces=ftseismic.traces(1:nsamp,:);
switch param.output
case 'amp'
ftseismic.traces=abs(ftseismic.traces);
ftseismic.name=['Amplitude spectrum of "',seismic.name,'"'];
htext='Amplitude spectrum';
case 'ft'
% Use "twiddle" factor to correct the phase so that the spectrum
% honors time zero; consequently, a data set symmetric about time zero
% will have a zero imaginary part; one anti-symmetric about time zero will
% have a purely imaginary Fourier transform (within rounding errors)
twf=exp((-2*pi*seismic.first/(nfft*seismic.step)*i)*(0:nsamp-1)).';
for ii=1:size(seismic.traces,2)
ftseismic.traces(:,ii)=ftseismic.traces(:,ii).*twf;
end
htext='Fourier transform';
ftseismic.name=['Fourier transform of "',seismic.name,'"'];
otherwise
error(['Unknown output option: ',param.output])
end
% Append history field
if isfield(seismic,'history')
ftseismic=s_history(ftseismic,'append',htext);
end
|
github
|
Abakumov/MLIB-master
|
s_gain.m
|
.m
|
MLIB-master/OTHER/SeisLab_10.0301/S4M/Geophysics_3.0/s_gain.m
| 5,350 |
utf_8
|
f222c041256013eb3a17b6eda3f10b71
|
function [gseismic,tgain]=s_gain(seismic,varargin)
% Function computes and applies a gain function to the input data set and
% outputs the gained data set as well as the gain function (if two output
% data sets are specified)
%
% Written by: E. Rietsch: July 14, 2000
% Last updated: October 2, 2001: Handle NaNs in data (at least in some cases}
%
% [gseismic,tgain]=s_gain(seismic,varargin)
% INPUT
% seismic seismic data structure
% varagin one or more cell arrays; the first element of each cell array is
% a keyword, the other elements are parameters.
% Presently, keywords are:
% 'type' Type of gain. Possible values are 'trace' (each trace is
% gained individually) and 'dataset' (one gain for the whole data set).
% Default: {type','trace'}
% 'average' Type of average to use when one gain is used for the whole dataset.
% Possible values are: 'mean' (i.e. mean of absolute values) and
% 'median' (i.e. median of absolute values).
% Default: {average','median'}
% 'wlength' Window length (ms) for automatic gain calculation.
% Default: {'wlength',500)
% OUTPUT
% gseismic seismic data structure with gained input data set
% tgain gain applied to input seismic data set.
if ~isstruct(seismic)
error(' First input argument must be seismic structure')
end
[nsamp,ntr]=size(seismic.traces);
% Set default values
param.average='median';
param.type='trace';
param.window=[];
param.wlength=500;
% Replace defaults by actual input arguments
param=assign_input(param,varargin);
%
if ~isempty(param.window)
param.wlength=param.window;
alert('Parameter "window" is obsolete; replace it with "wlength".')
end
% Set window length in samples
wlength=fix(param.wlength/seismic.step)+1;
if wlength > nsamp
wlength=nsamp;
end
if ~mod(wlength,2)
wlength=max(wlength-1,1);
end
if isnull(seismic)
if 1
error(' NaNs in seismic dataset not yet allowed.')
end
if strcmpi(param.type,'trace')
tgain_traces=trace_gain(seismic.traces,wlength);
gseismic.traces=seismic.traces./tgain_traces;
htext='trace gain';
elseif strcmpi(param.type,'dataset')
tgain_traces=trace_gain4nans(seismic.traces,wlength);
gseismic.traces=seismic.traces./tgain_traces;
htext='suite gain';
else
error('Unknown gain type')
end
else
if strcmpi(param.type,'trace')
tgain_traces=trace_gain(seismic.traces,wlength);
gseismic.traces=seismic.traces./tgain_traces;
htext='trace gain';
elseif strcmpi(param.type,'dataset')
% nsamp=size(seismic.traces,1);
tgain_traces=suite_gain(seismic.traces,wlength,param.average);
for ii=1:ntr
gseismic.traces(:,ii)=seismic.traces(:,ii)./tgain_traces;
end
htext='suite gain';
else
error('Unknown gain type')
end
end
% Copy rest of fields
gseismic=copy_fields(seismic,gseismic);
% Append history field
htext=[htext,', window length = ',num2str(param.wlength),' ',seismic.units];
gseismic=s_history(gseismic,'append',htext);
% Convert tgain to seismic structure
if nargout > 1
tgain=s_convert(tgain_traces,seismic.first,seismic.step, ...
seismic.units);
tgain=s_history(tgain,'add',htext);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function gain=suite_gain(in,wl,average)
% Function computes time-varying gain over window of wl samples length for
% the whole dataset
% gain=tv_gain(in,wl,average)
% INPUT
% in input traces
% wl window length in samples (should be odd);
% average type of averaging ('mean' or 'median')
% OUTPUT
% gain gain function
wlh=floor(wl/2);
if strcmpi(average,'mean')
amps=mean(abs(in),2);
else
amps=median(abs(in),2);
end
amps=[0;cumsum(amps)];
gf=amps(wl+1:end)-amps(1:end-wl);
ga=gf(1);
ge=gf(end);
gain=[ga(ones(wlh,1),:);gf;ge(ones(wlh,1))]+eps;
gain=gain/mean(gain);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function gain=trace_gain(in,wl)
% Function computes, for each trace, time-varying gain over window of wl samples length
% gain=trace_gain(in,wl)
% INPUT
% in input traces
% wl window length in samples (should be odd);
% OUTPUT
% gain gain function
m=size(in,2);
wlh=floor(wl/2);
amps=[zeros(1,m);cumsum(abs(in))];
gf=amps(wl+1:end,:)-amps(1:end-wl,:);
ga=gf(1,:);
ge=gf(end,:);
gain=[ga(ones(wlh,1),:);gf;ge(ones(wlh,1),:)]+eps;
mgain=mean(gain(:));
for ii=1:m
gain(:,ii)=gain(:,ii)/mgain;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function gain=trace_gain4nans(in,wl)
% Function computes, for each trace, time-varying gain over window of wl samples length
% gain=trace_gain(in,wl)
% INPUT
% in input traces
% wl window length in samples (should be odd);
% OUTPUT
% gain gain function
wlh=floor(wl/2);
[n,m]=size(in);
scf=ones(n+1,m);
lidx=isnan(in);
in(lidx)=0;
scf(lidx)=0;
scf=cumsum(scf);
amps=[zeros(1,m);cumsum(abs(in))];
gf=(amps(wl+1:end,:)-amps(1:end-wl,:))./(scf(wl+1:end,:)-scf(1:end-wl,:)+eps);
ga=gf(1,:);
ge=gf(end,:);
gain=[ga(ones(wlh,1),:);gf;ge(ones(wlh,1),:)]+eps;
mgain=mean(gain(:));
for ii=1:m
gain(:,ii)=gain(:,ii)/mgain;
end
|
github
|
Abakumov/MLIB-master
|
read_segy_file_legacy.m
|
.m
|
MLIB-master/OTHER/SeisLab_10.0301/S4M/Geophysics_3.0/read_segy_file_legacy.m
| 29,371 |
utf_8
|
729705da2c0c1ef1a6307004d5070f98
|
function [seismic,ebcdic_header,binary_header]=read_segy_file_legacy(filename,varargin)
% Function reads a SEG-Y file and outputs a seismic structure
%
% Written by: E. Rietsch: March 5, 2000
% Last updated: April 6, 2007: fix bug in reading of user-specified headers
%
% [seismic,ebcdic_header,binary_header]=read_segy_file_legacy(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,description}, ...
% {mnem2,first,bytes,units,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}; all samples with times between (and including)
% first and last (in ms) are output.
% Default: {'times',[]} i.e. all times
% traces select traces to output; this cell array has the form
% {'traces',criterion}; the variable "criterion" is used to
% determine which traces to output. "criterion" 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}
%
% 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.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.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
%
% [seismic,ebcdic_header,binary_header]=read_segy_file(filename,varargin)
global S4M ABORTED
ABORTED=false;
seismic=[];
ebcdic_header=[];
binary_header=[];
run_presets_if_needed
% Set default parameters
param.format='header';
param.headers={};
param.ignoreshift=false;
param.times=[];
param.traces=[];
if ~isempty(varargin)
param=assign_input(param,varargin); % Interpret/check input data
end
if strcmpi(param.format,'ieee')
param.format='ieee-be';
end
o_format='ieee-be';
if nargin < 1
filename='';
end
if nargout < 2
parameters=initiate_segy_file_reading_no1(filename,param,o_format);
elseif nargout == 2
[parameters,ebcdic_header]=initiate_segy_file_reading_no1(filename,param,o_format);
else
[parameters,ebcdic_header,binary_header]=initiate_segy_file_reading_no1(filename,param,o_format);
end
if ABORTED
return
end
param.format=parameters.format;
fid=parameters.fid;
seismic=parameters.seismic;
indices2=parameters.indices2;
indices4=parameters.indices4;
idx_time=parameters.idx_time;
filename=parameters.filename;
no_samples=parameters.no_samples;
n_default_headers=parameters.n_default_headers;
nindices2=parameters.nindices2;
nindices4=parameters.nindices4;
[header,nh_select,max_traces,idx_trace,h_index,trace_select,param] = ...
select_traces(seismic,fid,param); %#ok h_index used in "eval"
ier=0;
% Reserve room for header and seismic
if max_traces <= 1000
grab=max_traces;
else
grab=1000;
grab_inc=grab;
end
txt=['Make room for ',num2str(grab),' traces'];
ltext=length(txt);
%fprintf('\n')
headers=zeros(size(seismic.header_info,1),grab);
seismic.traces=zeros(length(idx_time),grab);
ntraces=0;
ntraces_read=0;
% Read seismic trace header
four_bytes=zeros(60,1);
two_bytes=zeros(90,1);
test=fread(fid,1,'int32');
try % Catch errors due to premature end of SEG-Y file
while ~isempty(test) && ntraces < max_traces % read trace
ntraces_read=ntraces_read+1;
% trace_no=ntraces_read; % For use in trace selection
if ntraces >= grab
grab=grab+grab_inc;
headers=[headers,zeros(size(seismic.header_info,1),grab_inc)]; %#ok
seismic.traces=[seismic.traces,zeros(length(idx_time),grab_inc)]; %#ok
if S4M.alert
txt=['Make room for ',num2str(grab),' traces'];
if grab == 2*grab_inc
fprintf(txt)
else
fprintf([char(8*ones(1,ltext)),txt])
end
ltext=length(txt);
end
end
four_bytes(1)=test;
four_bytes(2:7)=fread(fid,6,'int32');
two_bytes(15:18)=fread(fid,4,'int16');
four_bytes(10:17)=fread(fid,8,'int32');
two_bytes(35:36)=fread(fid,2,'int16');
four_bytes(19:22)=fread(fid,4,'int32');
two_bytes(45:90)=fread(fid,46,'int16');
four_bytes(46:60)=fread(fid,15,'int32');
depth_scalar=two_bytes(35);
if depth_scalar > 0
four_bytes(11:17)=four_bytes(11:17)*depth_scalar;
elseif depth_scalar < 0
four_bytes(11:17)=four_bytes(11:17)/abs(depth_scalar);
else
if ier < 2, disp('Alert from "read_segy_file": Scalar for elevations and depths (bytes 69-70) is zero'); end
ier=ier+1;
end
coord_scalar=two_bytes(36);
if coord_scalar > 0
four_bytes(19:22)=four_bytes(19:22)*coord_scalar;
elseif coord_scalar < 0
four_bytes(19:22)=four_bytes(19:22)/abs(coord_scalar);
else
if ier < 2, disp('Alert from "read_segy_file": Scalar for coordinates (bytes 71-72) is zero'); end
ier=ier+1;
end
headers(:,ntraces+1)=[four_bytes(indices4(1:nindices4)); ...
two_bytes(indices2(1:nindices2)); ...
four_bytes(indices4(nindices4+1:end)); ...
two_bytes(indices2(nindices2+1:end))];
if trace_select == 0
boolean=ntraces < max_traces;
elseif trace_select == 1
for jj=1:nh_select
eval([header{jj},'=headers(h_index(jj),ntraces+1);']);
end
try
boolean=ntraces < max_traces && eval(param.traces);
catch
error([' The input argument ',param.traces, ...
' of read_segy_file is probably not a valid logical expression.'])
end
else
try
boolean=ntraces < max_traces && sum(ismember(idx_trace,ntraces_read));
catch
error([' The input argument ',param.traces, ...
' of read_segy_file is probably not a valid logical expression'])
end
end
% Read seismic trace
if strcmpi(param.format,'ibm') % IBM format (requires conversion)
%if ntraces < 10; disp(param.format); end %test
temp=fread(fid,no_samples,'uint');
if boolean
ntraces=ntraces+1;
seismic.traces(:,ntraces)=ibm2ieee(temp(idx_time ));
end
else % Other format (no conversion required)
% if ntraces < 10; disp('ieee'); end%test
temp=fread(fid,no_samples,'float32');
if boolean
ntraces=ntraces+1;
try
seismic.traces(:,ntraces)=temp(idx_time);
catch
% keyboard
end
end
end
test=fread(fid,1,'int32'); % Check if there is one more trace
end
catch
msgdlg('Prematude end of SEG-Y file or other file reading error.')
end
fclose(fid);
fprintf('\n')
if S4M.history
seismic=s_history(seismic,'add',filename);
end
% Remove unused reserved space
%seismic.traces=seismic.traces(:,1:ntraces);
seismic.traces(:,ntraces+1:end)=[];
headers(:,ntraces+1:end)=[];
% Remove headers with duplicate header mnemonics
if isfield(seismic,'header_info')
mnems=seismic.header_info(:,1);
lmnems=length(mnems);
% bool=logical(zeros(lmnems,1));
bool=false(lmnems,1);
if lmnems > 1
try
if length(unique(mnems)) < lmnems
for ii=lmnems-1:-1:2
bool1=ismember(mnems(1:ii),mnems(ii+1));
bool(1:ii)= bool1(1:ii) | bool(1:ii);
end
seismic.header_info(bool,:)=[];
headers(bool,:)=[];
end
catch
dbstack
ple
alert('An error of unknown orign has been cought.')
keyboard
end
end
end
% Remove header mnemonics that contain only zeros
nh=size(headers,1);
index=1:nh;
for ii=n_default_headers:-1:1;
% idx=find(headers(ii,:) ~= 0);
% if isempty(idx)
if all(headers(ii,:) == 0)
index(ii)=[];
end
end
if ~isempty(index)
seismic.header_info=seismic.header_info(index,:);
seismic.headers=headers(index,:);
% Check if Header "lag" still exists
[index,ier]=header_index1(seismic,'lag');
if ier == 0 && ~param.ignoreshift
disp('Seismic data shifted since header "lag" is not identically zero.')
disp(['Lag varies from ',num2str(min(seismic.headers(index,:))),' to ',num2str(max(seismic.headers(index,:)))])
seismic=s_shift(seismic,{'shifts',seismic.headers(index,:)});
end
else
seismic=rmfield(seismic,'header_info');
end
if seismic.aux_per_record == 0
seismic=rmfield(seismic,'aux_per_record');
end
if isempty(seismic.traces)
msgdlg([' Alert from "read_segy_file": No seismic traces read from file ',filename])
end
seismic.fp_format_of_segy_file=param.format;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [parameters,ebcdic_header,binary_header]=initiate_segy_file_reading_no1(filename,param,o_format)
global S4M ABORTED
parameters=[];
% Open the file
if ~isempty(filename)
fid=fopen(filename,'r',o_format);
if fid == -1
if ~S4M.deployed
fprintf(['... unable to find file ',filename,'\n']);
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',o_format);
if fid < 0
error(['File "',filename,'" could not be opened.'])
end
end
% Read EBCDIC reel header 1
header_ebcdic=fread(fid,3200,'uchar');
if isempty(header_ebcdic)
errordlg('EBCDIC header is empty; requested file is either empty or not an SEG-Y file.', ...
S4M.name)
ABORTED=true;
end
if nargout > 1
ebcdic_header=char(ebcdic2ascii(reshape(header_ebcdic,80,40)'));
end
% Read binary real 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);
if nargout > 2
binary_header=two_bytes;
end
seismic.type='seismic';
seismic.tag='unspecified';
[dummy,name]=fileparts(S4M.filename); %#ok First output variable is not required
seismic.name=name;
seismic.from=fullfile(S4M.pathname,S4M.filename);
seismic.line_number=four_bytes(2);
seismic.reel_number=four_bytes(3);
seismic.traces_per_record=two_bytes(7);
seismic.aux_per_record=two_bytes(8);
seismic.first=0;
seismic.step=two_bytes(9)/1000;
no_samples=two_bytes(11);
seismic.last=seismic.step*(no_samples-1);
seismic.units='ms';
if two_bytes(13) == 1
if strcmpi(param.format,'header') || strcmpi(param.format,'ibm')
param.format='ibm';
else
display('IEEE format requested')
warning(warnid,['Data apparently stored as 32-bit IBM floating point numbers; ' ...
'data sample format code = ',num2str(two_bytes(13))]);
end
elseif two_bytes(13) == 5
if strcmpi(param.format,'header') || strcmpi(param.format,'ieee-be')
param.format='ieee-be';
else
display('IBM format requested')
warning(warnid,['Data apparently stored as 32-bit IEEE big-endian floating point numbers; ' ...
'data sample format code = ',num2str(two_bytes(13))]);
end
else
myerror(['Data in unsupported format; ' ...
'data sample format code = ',num2str(two_bytes(13))]);
if ABORTED
fclose(fid)
return
end
end
if two_bytes(14) ~= 0
seismic.cdp_fold=two_bytes(14);
end
if two_bytes(28) == 1
units='m';
elseif two_bytes(28) == 2
units='ft';
else
units='unknown';
end
[seismic,idx_time]=select_times(seismic,no_samples,fid,param);
% Compute indices of two-byte and four-byte header words which are to be saved
% by default
indices2=([29;109]-1)/2+1;
indices4=([1;9;13;17;21;25;37;49;61;65;73;77;45;81;85;41;181;185;189;193]-1)/4+1;
nindices2=length(indices2);
nindices4=length(indices4);
i_lag=nindices4+2; % Index of lag
[seismic,indices2,indices4,n_default_headers] = ...
select_headers(seismic,units,indices2,indices4,i_lag,param);
parameters.fid=fid; % File ID
parameters.seismic=seismic; % Seismic structure without traces and headers
parameters.indices2=indices2; % Indices of 2-byte headers
parameters.indices4=indices4; % Indices of 4-byte headers
parameters.idx_time=idx_time; % indices of trace samples to output
parameters.format=param.format; % Data format to read
parameters.no_samples=no_samples; % Number of samples per trace input
parameters.filename=filename; % Name of SEG-Y file
parameters.traces=param.traces; % Parameters controlling trace selection
parameters.n_default_headers=n_default_headers; % Number of headers read by default
parameters.i_lag=i_lag; % Description index of lag
parameters.nindices2=nindices2;
parameters.nindices4=nindices4;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [header,nh,max_trace,idx_trace,h_index,trace_select,param] = ...
select_traces(seismic,fid,param)
% Function creates parameters which control which traces are output
if isempty(param.traces)
max_trace=inf;
idx_trace=[];
h_index=[];
trace_select=0;
header=[];
nh=[];
elseif ischar(param.traces) % Compute criteria for outputting/discarding traces
trace_select=1;
max_trace=inf;
idx_trace=[];
param.traces=lower(param.traces);
header=unique(extract_words(param.traces));
nh=length(header);
if nh == 0
fclose(fid);
error([' No header in trace constraint ',param.traces])
end
h_index=zeros(nh,1);
counter=0;
for ii=1:nh
temp=find(ismember(seismic.header_info(:,1),lower(header(ii))));
if ~isempty(temp)
if length(temp) > 1
disp([' More than one header with mnemonic "',header{ii},'" found when '])
disp(' analyzing the trace-selection constraints.')
disp(' Probably caused by explicitely requesting a header that is already ')
disp(' read by default and then using it in the constraint.')
pause(0)
error(' Abnormal termination')
end
counter=counter+1;
header(counter)=header(ii);
h_index(counter)=temp;
end
end
nh=counter;
else
trace_select=2;
idx_trace=param.traces;
h_index=[];
try
max_trace=max(idx_trace);
catch
disp(' Apparently wrong syntax using keyword "traces"')
error(' Abnormal termination')
end
header=[];
nh=[];
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [seismic,idx_time]=select_times(seismic,no_samples,fid,param)
% Function sets parameter that determine the time range to output
if iscell(param.times)
param.times=cat(2,param.times{:});
end
% Selection criteria for traces and times
if ~isempty(param.times) % Compute index vector for time samples
param.times(1)=ceil(param.times(1)/seismic.step)*seismic.step;
if param.times(1) > 0
seismic.first=param.times(1);
end
if param.times(2) < seismic.first
fclose(fid);
error([' Selected end time (',num2str(param.times(2)), ...
') smaller than start time (',num2str(seismic.first),')']);
end
if param.times(2) < seismic.last
seismic.last=fix(param.times(2)/seismic.step)*seismic.step;
end
ita=ceil(seismic.first/seismic.step)+1;
ite=floor(seismic.last/seismic.step)+1;
idx_time=(max([1,ita]):min([ite,no_samples]))';
if isempty(idx_time)
fclose(fid);
error(' No time samples selected. Check parameter "times"')
end
else
idx_time=(1:no_samples)'; % Keep all time samples
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [seismic,indices2,indices4,n_default_headers]= ...
select_headers(seismic,units,indices2,indices4,i_lag,param)
% Function sets parameters which contol what headers to output
%global param
% Select standard headers and add user-defined headers
% Descriptions for standard binary trace headers
seismic.header_info(:,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'}; ...
{'Sourface 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'}; ...
];
seismic.header_info(:,1)=[ ... % 4-byte headers
{'ds_seqno'}; ...
{'ffid'}; ...
{'o_trace_no'}; ...
{'source'}; ...
{'cdp'}; ...
{'seq_cdp'}; ...
{'offset'}; ...
{'depth'}; ...
{'sou_h2od'}; ...
{'rec_h2od'}; ...
{'sou_x'}; ...
{'sou_y'}; ...
{'sou_elev'}; ...
{'rec_x'}; ...
{'rec_y'}; ...
{'rec_elev'}; ...
{'cdp_x'};...
{'cdp_y'}; ...
{'iline_no'}; ...
{'xline_no'}; ...
{'trc_type'}; ... % 2-byte headers
{'lag'}; ...
];
n_default_headers=size(seismic.header_info,1);
seismic.header_info(1:n_default_headers,2)=deal({'n/a'});
seismic.header_info(7:16,2)={units};
seismic.header_info(i_lag,2)={'ms'};
% 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={units,'X-coordinate of CDP'};
defaults.cdp_y={units,'Y-coordinate of CDP'};
if isempty(param.headers)
nh=0;
elseif ~iscell(param.headers{1})
param.headers={param.headers};
nh=1;
else
nh=length(param.headers);
end
add=cell(nh,5);
for ii=1:nh
nh1=length(param.headers{ii});
add(ii,1:nh1)=param.headers{ii};
if nh1 == 5
if isempty(add{ii,4}); add(ii,4)={'n/a'}; end
if isempty(add{ii,5}); add(ii,5)={'not available'}; end
else
if sum(ismember(fieldnames(defaults),lower(add{ii,1})))
% add(ii,4:5)=getfield(defaults,lower(add{ii,1}));
add(ii,4:5)=defaults.(lower(add{ii,1}));
else
add(ii,4:5)={'n/a','not available'};
end
end
end
get.mnem=add(:,1);
get.first=add(:,2);
get.bytes=add(:,3);
get.units=add(:,4);
get.descriptions=add(:,5);
nheader=size(get.mnem,1);
for jj=1:nheader
if get.bytes{jj} == 2
strt=(get.first{jj}-1)/2+1;
if fix(strt) ~= strt
error(['First byte for header ',get.mnem{jj}, ' is wrong'])
end
indices2=[indices2;strt]; %#ok
else
strt=(get.first{jj}-1)/4+1;
if fix(strt) ~= strt
error(['First byte for header ',get.mnem{jj}, ' is wrong'])
end
indices4=[indices4;strt]; %#ok
end
end
seismic.header_info=cat(1,seismic.header_info, ...
cat(2,lower(get.mnem(:)),get.units(:),get.descriptions(:)));
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
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);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function d = ibm2ieee (ibmf)
% Name: ibm2ieee
% Abstract: convert a matrix of IBM/360 32-bit floats
% to IEEE doubles.
%
% IBMF is the matrix of IBM/360 32-bit floats each
% stored as a 32 bit unsigned big-endian integer
% in a MATLAB double.
%
% The format of a IBM/360 32-bit float is:
%
% sign 7-bit exponent 24 bit fraction
% The base is 16. The decimal point is to
% the left of the fraction. The exponent is
% biased by +64.
%
% The basic idea is that you use floating point on
% the various fields.
%
% ieee = sign * 16 ^ (exponent - 64) * fraction / 16 ^ 6
%
% By: Martin Knapp-Cordes
% The MathWorks, Inc.
%
% Date(s): Jun 95 - 28, 29
% $Revision: 1.2 $ $Date: 1995/06/29 14:50:03 $
% This M-file is not officially supported by The MathWorks, Inc. Please use
% it as is, or modify it to your specific need
%
%Assuming you have a file, which contains IBM float 32 format binary data, called
%5702.seg, then you must use the following FOPEN and FREAD call the read the
%file:
%
% fid = fopen('5702.seg','r','b');
%
%%
%% Read first data record - IBM/360 32-bit floating format
%% Read them as unsigned (32-bit) integers.
%% Convert to IEEE doubles using ibm2ieee.
%%
%% size - number of elements to read
%
% ibm1 = fread(fid,size,'uint');
% ieee1 = ibm2ieee(ibm1);
%----------------------------------------------------------------------------
%
if (nargin ~= 1)
error ('Wrong number of arguments.');
elseif (isempty(ibmf))
error ('Argument is an empty matrix');
end
%
aibmf = sprintf('%08x',ibmf);
%
% hexd(1) - 1st hex digit - first bit is sign, next 3 bits high order exponent
% hexd(2) - 2nd hex digit - bits of low order exponent
% hexd(3) - 3rd-8th hex digit - bits of fraction
%
hexd = sscanf(aibmf,'%1x%1x%6x',[3,inf]);
d = (1 - (hexd(1,:) >= 8) .* 2) .* ...
16 .^ ((hexd(1,:) - (hexd(1,:) >= 8) .* 8) .* 16 + hexd(2,:) ...
- 70).* hexd(3,:);
d = reshape(d,size(ibmf));
|
github
|
Abakumov/MLIB-master
|
s_trace_numbers.m
|
.m
|
MLIB-master/OTHER/SeisLab_10.0301/S4M/Geophysics_3.0/s_trace_numbers.m
| 5,359 |
utf_8
|
c33260b8dcdf5c6d0a821145c65e76f8
|
function [index,ierr]=s_trace_numbers(seismic,string,varargin)
% Function outputs trace numbers of seismic input traces based on
% selected header values.
% See also: "s_select"
%
% Written by: E. Rietsch: April 15, 2000
% Last updated: July 23, Revamped code
%
% [index,ierr]=s_trace_numbers(seismic,string,varargin)
% INPUT
% seismic seismic structure
% string the string it can be a header mnemonic or it can contain a
% logical expression involving header mnemonics and header values.
% A "pseudo-header" 'trace_no' can also be used.
% varargin one or two arguments if "string" is a header mnemonic.
% If there is only one argument it is a vector of header values
% e.g. s_trace_numbers(seismic,'cdp',100:200)
% If there are two arguments they denote the lower and upper limit of
% header values
% e.g. s_trace_numbers(seismic,'cdp',100,200)
% OUTPUT
% index column vector with indices of trace numbers
% ierr error code
% no error: ierr = 0
% Header has no values matching the ones requested: ierr = 1
% Header has no values within range specified: ierr = 2
% No header mnemonics found in expression: ierr = 3
% Not a valid logical expression: ierr = 4
% If the second output argument is not supplied and an error occurs
% the function aborts with the appropriate error message
%
% EXAMPLES OF USAGE
% index=s_trace_numbers(seismic,'offset',[100:100:2000])
% index=s_trace_numbers(seismic, ...
% 'iline_no > 1000 && iline_no < 1100 && xline_no == 1000')
% EXAMPLES
% seismic=s_data;
% index1=s_trace_numbers(seismic,'ismember(cdp,[106,107,108])')
% index1a=s_trace_numbers(seismic,'cdp',106,108)% This is equivalent to
% % the previous command
% index1b=s_trace_numbers(seismic,'cdp',106:108)% This is equivalent to
% % the previous command
%
% index1x=s_trace_numbers(seismic,'cdp',[106,106.5,108])
% index1y=s_trace_numbers(seismic,'cdp',[107,106,108])
%
% index2=s_trace_numbers(seismic,'cdp',105,inf)
% index2a=s_trace_numbers(seismic,'cdp >= 105') % This is equivalent to
% % the previous command
% UPDATE HISTORY
% September 13, 2004: Second output argument
if ~istype(seismic,'seismic')
error('First input argument "seismic" must be a structure.')
end
ierr=0;
if nargin < 2
error('There must be at least 2 input arguments')
end
if nargin == 2 % Traces defined via logical expression
[index,ierr]=find_trace_index(seismic,string);
elseif nargin == 3 % Header values given explicitly
header_vals=s_gh(seismic,string);
hidx=varargin{1};
index=ismember_ordered(header_vals,hidx);
index=reshape(index,1,[]);
if isempty(index)
if nargout <= 1
disp(' Requested header values:')
disp(hidx)
error(['Header "',header,'" has no values matching the ones requested'])
else
ierr=1;
index=[];
end
end
elseif nargin == 4 % First and last header value specified
header_vals=s_gh(seismic,string);
ha=varargin{1};
he=varargin{2};
index=find(header_vals >= ha & header_vals <= he);
if isempty(index)
if nargout <= 1
error(['Header "',header,'" has no values within range specified (',num2str([ha,he]),')'])
else
ierr=2;
index=[];
end
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [index,ierr]=find_trace_index(seismic,expression)
% Function finds index of traces whose header values match a logical expression
%
% INPUT
% seismic seismic data set
% expression logical expression involving header values
% OUTPUT
% index index of trace numbers (traces "seismic.traces(:,index)" are selected)
% ierr error code
global S4M
ierr=0;
words=lower(unique(extract_words(expression))); % Find all the words in the logical expression
% Find all the header mnemonics in "words" and assign header values to variables with those names
if S4M.case_sensitive
idx=find(ismember(seismic.header_info(:,1),words));
else
idx=find(ismember(lower(seismic.header_info(:,1)),words));
end
if isempty(idx) && sum(ismember(words,'trace_no')) == 0
disp([' No header mnemonics found in expression "',expression,'"'])
disp(' header mnemonics available')
disp(seismic.header_info(:,1)')
if nargout == 1
error(' Abnormal termination')
else
ierr=3;
index=[];
return
end
end
nh=length(idx);
for ii=1:nh
eval([lower(char(seismic.header_info(idx(ii),1))),' = seismic.headers(idx(ii),:);']);
end
try
index=eval(['find(',lower(expression),')']);
catch
disp([' The argument of keyword "traces" (',expression,')'])
disp(' is probably not a valid logical expression')
if nargout == 1
error(' Abnormal termination')
else
ierr=4;
index=[];
end
end
|
github
|
Abakumov/MLIB-master
|
l_regression.m
|
.m
|
MLIB-master/OTHER/SeisLab_10.0301/S4M/Geophysics_3.0/l_regression.m
| 11,715 |
utf_8
|
f87084a49b48291ff434624c4f75c782
|
function [wlog,aux]=l_regression(wlog,expression,varargin)
% Function creates new log curve using the mathematical expression contained in the
% third input argument. Null values (NaNs) in the log curves are ignored when computing
% the regression parameters. Requires the Optimization Toolbox
%
% Written by E. Rietsch, March 16, 2001
% Last updated: July 8, 2006: Use dynamic field names; updated
%
% [wlog,aux]=l_regression(wlog,expression,varargin)
% INPUT
% wlog log structure
% expression expression in MATLAB syntax between curves of wlog. These curves are
% represented by their mnemonics. No default.
% EXAMPLE: 'rho = x1*Vp^x2' which estimates a Gardner-type relationship
% for the density
% The curve to the left of the equal sign is called the target curve
% ('rho' in this example)
% The parameters to be estimated are represented by "x1","x2",...,"x9".
% varargin one or more cell arrays; the first element of each cell array is a
% keyword, the other elements are parameters. Presently, keywords are:
% 'depths' start and end depth of curves used for regression calculation
% Default: {'depths',wlog.first,wlog.last}
% 'rows' string with logical expression involving one more of the curve mnemonics
% Can be used to restrict curve values used for regression to certain lithologies
% Default: {'rows',''} (implies all rows)
% 'lbounds' lower limits for the values of the parameters to be
% estimated.
% No defaults.
% 'ubounds' upper limits for the values of the parameters to be
% estimated.
% No defaults.
% 'description' description of the newly created curve
% 'x' initial values of the parameters
% Default: {'x',0.5*(ubounds-lbounds)}
% Error message if any of the bounds are infinite.
% 'mnem' mnemonic of the estimated curve.
% Default: {'mnem','curve_pred'} where "curve" is the mnmonic of the
% target curve in "expression"; in the example above it
% would be 'rho_pred')
% 'norm' Norm to use; possible values are 'L1' (minimizes the sum of the
% absolute values of the error; more robust) or 'L2' (sum of the
% squares of the error; faster). If norm is 'L1', two additional parameters
% may be given which allow treating positve deflections different from
% negative ones. Not case-sensitive.
% Default: {'norm','L1')
% OUTPUT
% wlog input log with the additional curve appended (including an updated field
% "curve_info")
% aux structure with auxiliary information. The following fields are present:
% x1, x2, ... estimated parameters;
% x estimated paramters as a row vector
% fval final function value (error)
% exitflag of the minimization routine
% general info from minimization routine (important only for debugging)
%
% EXAMPLES
% wlog=l_data;
%
% % Density from velocity
% [wlog,aux]=l_regression(wlog,'rho=x1*vp^x2');
% l_plot1(wlog,{'curves','rho','rho_pred'})
%
% % Depth trend of density
% [wlog,aux]=l_regression(wlog,'rho=x1*depth^x2',{'mnem','rho_trend'});
% l_plot1(wlog,{'curves','rho','rho_trend'})
% Set defaults of input arguments
param.depths=[];
param.rows=[];
param.lbounds=[];
param.ubounds=[];
% param.description='';
param.x=[];
param.mnem=[];
param.norm='l1';
% Decode and assign input arguments
param=assign_input(param,varargin);
% Find all the words in the expression
words=extract_words(expression);
% Check if mnemonic of output curve (first variable in expression) exists
mnem=words{1};
[index,ier]=curve_index1(wlog,mnem,0);
if ier
if isempty(index)
disp([char(13),' No curve with mnemonic "',mnem,'" found in log structure'])
else
disp([char(13),' More than one curve with mnemonic "',mnem,'" found in log structure'])
end
error(' Abnormal termination')
end
% Set default name for target curve (if not defined in argument list)
if isempty(param.mnem)
param.mnem=[mnem,'_pred'];
end
nsamp=size(wlog.curves,1);
% words=extract_words(expression);
vars=symvar(expression);
% Find all the parameters
x1to9={'x1','x2','x3','x4','x5','x6','x7','x8','x9'};
lindex=ismember(vars,x1to9);
xi=vars(lindex);
lxi=length(xi);
% Check initial values for parameters
if ~isempty(param.x)
if length(param.x) ~= lxi
disp([char(13),' Discrepancy: ',num2str(lxi),' parameters found in expression, but ', ...
num2str(length(param.x)),' initial value(s) found'])
error(' Abnormal termination')
end
if iscell(param.x)
param.x=cat(2,param.x{:});
end
end
% Check bounds of parameters
if isempty(param.lbounds)
param.lbounds=-inf*ones(1,lxi);
else
if length(param.lbounds) ~= lxi
disp([char(13),' Number of lower bounds (',num2str(length(param.lbounds)), ...
') not equal to number of parameters in expression (', ...
num2str(lxi),')'])
disp(' Check number of values entered via keyword "lbounds"')
error(' Abnormal ternination')
end
if iscell(param.lbounds)
param.lbounds=cat(2,param.lbounds{:});
end
end
if isempty(param.ubounds)
param.ubounds=inf*ones(1,lxi);
else
if length(param.ubounds) ~= lxi
disp([char(13),' Number of upper bounds (',num2str(length(param.ubounds)), ...
') not equal to number of parameters in expression (', ...
num2str(lxi),')'])
disp(' Check number of values entered via keyword "ubounds"')
error(' Abnormal ternination')
end
if iscell(param.ubounds)
param.ubounds=cat(2,param.ubounds{:});
end
end
if isempty(param.x)
param.x=0.5*(param.ubounds+param.lbounds);
if any(isinf(param.x))
error('There is no default for the starting values if any of the bounds are infinite.')
end
idx=find(isnan(param.x));
if ~isempty(idx)
for ii=1:length(idx)
if param.lbounds(idx(ii)) > -inf
param.x(idx(ii))=param.lbounds(idx(ii)) + 1;
elseif param.ubounds(idx(ii)) < inf
param.x(idx(ii))=param.ubounds(idx(ii)) - 1;
else
param.x(idx(ii))=0;
end
end
end
end
% Check if the initial values of the parameters are within the bounds
%temp=find(param.x < param.lbounds);
ier=0;
if any(param.x < param.lbounds)
ier=1;
alert(' One or more initial parameter values are below the lower bounds.')
end
%temp=find(param.x > param.ubounds);
if any(param.x > param.ubounds)
ier=1;
alert(' One or more initial parameter values are above the upper bounds.')
end
if ier
disp(' Initial parameter values:')
disp(param.x)
error(' Abnormal termination')
end
% Find all the curves ...
curve_names=vars(~lindex);
lp=length(curve_names);
% Check if "expression" is a valid MATLAB expression
for ii=1:lxi
eval([xi{ii},'=param.x(ii);']);
end
for ii=1:lp
eval([curve_names{ii},'=1;']);
end
try
eval([expression,';'])
catch
disp([char(13),' It is very likely, that "',expression,'" is not a valid MATLAB expression']);
error(' Abnormal termination')
end
% Check if there are selection criteria regarding depth range and rows
if ~isempty(param.depths) || ~isempty(param.rows)
if ~isempty(param.depths)
temp=l_select(wlog,{'depths',param.depths{1},param.depths{2}});
if ~isempty(param.rows)
temp=l_select(temp,{'rows',param.rows});
end
else
temp=l_select(wlog,{'rows',param.rows});
end
[aux,rhs_expression]=find_parameters(temp,expression,xi,param,curve_names);
else
[aux,rhs_expression]=find_parameters(wlog,expression,xi,param,curve_names);
end
% Create new curve with the parameters just estimated and add it
% to input log structure
curves=zeros(nsamp,lp);
for ii=1:lp
if ~strcmpi(curve_names(ii),mnem)
curves(:,ii)=l_gc(wlog,curve_names{ii});
end
end
x=aux.x; %#ok Used in "eval" below
test=sum(curves,2);
lindex=find(~isnan(test));
curves=curves(lindex,:); %#ok Used in "eval" below
temp=eval(rhs_expression);
new_curve=NaN*zeros(nsamp,1);
new_curve(lindex)=temp;
wlog=l_curve(wlog,'add_ne',param.mnem,new_curve,l_gu(wlog,mnem), ...
[l_gd(wlog,mnem),' (predicted)']);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [aux,rhs_expression]=find_parameters(wlog,expression,xi,param,curve_names)
nsamp=size(wlog.curves,1);
lxi=length(param.x);
% ... and copy them into matrix "curves", ...
lp=length(curve_names);
curves=zeros(nsamp,lp);
for ii=1:lp
eval(['curves(:,ii)=l_gc(wlog,''',curve_names{ii},''');']);
end
% curves_orig=curves;
% ... remove all null values
test=sum(curves,2);
% idx=find(~isnan(test));
curves=curves(~isnan(test),:);
% Check if there are enough curve samples left
if size(curves,1) < lxi
error(' Not enough valid sampes in requested curves')
end
% Transform "expression" into the objective function to be minimized
% 1. Modify expression to be valid for vectors
expr=strrep(expression,'*','.*');
expr=strrep(expr,'/','./');
expr=strrep(expr,'^','.^');
% 2. replace x1, x2, ... by x(1),x(2),...
for ii=1:lxi
expr=strrep(expr,xi{ii},['x(',num2str(ii),')']);
end
% 3. replace "=" sign by "-" sign
idx=findstr(expr,'=');
if length(idx) ~= 1
disp([char(13),' No equal sigh (=) found in expression "',expr])
error(' Abnormal termination')
end
expr1=[expr(1:idx-1),'-(',expr(idx+1:end),')'];
rhs_expression=expr(idx+1:end);
% 4. replace header mnemonics by columns of array,...
funct=expr1;
for ii=1:lp
funct=strrep(funct,curve_names{ii},['curves(:,',num2str(ii),')']);
rhs_expression=strrep(rhs_expression,curve_names{ii},['curves(:,',num2str(ii),')']);
end
% 5. define objective function for the minimization condition
if ischar(param.norm)
if strcmpi(param.norm,'L1')
min_cond=['sum(abs(',funct,'))'];
elseif strcmpi(param.norm,'L2')
min_cond=['norm(',funct,')'];
else
disp([char(13),' Unknown norm "',param.norm,'"'])
error(' Abnormal termination')
end
else
if strcmpi(param.norm{1},'L1')
funct1=['(',expr1,')'];
funct2=funct1;
for ii=1:lp
funct1=strrep(funct1,curve_names{ii},['curves(',funct,' > 0,',num2str(ii),')']);
funct2=strrep(funct2,curve_names{ii},['curves(',funct,' < 0,',num2str(ii),')']);
end
min_cond=[num2str(param.norm{3}),'*','sum(abs(',funct1,')) + ', ...
num2str(param.norm{2}),'*','sum(abs(',funct2,'))'];
else
disp([char(13),' Unknown norm "',param.norm,'" or parameters missing from "L1"'])
error(' Abnormal termination')
end
end
% Create inline function for the objective function
ifunct=inline(min_cond,'x','curves');
options=optimset('MaxFunEvals',5000,'LargeScale','off');
if isempty(param.lbounds) && isempty(param.ubounds)
% Perform unconstrained minimization
[x,fval,exitflag,output]=fminunc(ifunct,param.x,options,curves);
else % Perform constrained minimization
[x,fval,exitflag,output]=fmincon(ifunct,param.x,[],[],[],[],param.lbounds,param.ubounds, ...
[],options,curves);
end
% Prepare output
aux=[];
for ii=1:lxi
% aux=setfield(aux,xi{ii},x(ii));
aux.(xi{ii})=x(ii);
end
aux.x=x;
aux.fval=fval;
aux.exitflag=exitflag;
aux.output=output;
|
github
|
Abakumov/MLIB-master
|
s_wplot.m
|
.m
|
MLIB-master/OTHER/SeisLab_10.0301/S4M/Geophysics_3.0/s_wplot.m
| 25,635 |
utf_8
|
b3fbf08aebc816369743a60a91d33bb4
|
function aux=s_wplot(seismic,varargin)
% Plot seismic data in wiggle-trace, variable-area form or as spikes at the
% sample times (the latter option is meant for the display of reflection coefficients)
%
% See also: s_cplot, s_plot, s_compare
%
% Written by: E. Rietsch: April 15, 2000
% Last updated: July 15, 2009: Replace two menu buttons by one menu. Replace
% keyword "wiggle" by "wiggle_color"
%
% aux=s_wplot(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' 2-element or 3-element cell array. Defines a header
% mnemonic whose values are used to annotate the horizontal axis.
% Default: {'annotation','trace_no'}
% 'aindex' annotation index; used to specify which traces to annotate with the
% value of the header selected via keyword annotation.
% Example {'aindex',10:10:1000} every tenth trace annotated,
% starting with trace 10
% It is not an error if the upper limit of 'aindex'
% (in this case 1000) exceeds the number of traces to
% be plotted.
% Default: {'aindex',[]} use Matlab-default annotation
% 'background' background color; possible options are the standard
% colors (or their abbreviations) and gray.
% Default: {'background','white'}
% 'deflection' trace deflection in units of trace spacing.
% Default: {'deflection',1.5} for seismic data
% 'direction' 2-element cell array defining plot direction. Possible values are:
% left-to-right, 'l2r', and right-to-left, 'r2l'.
% Default: {'direction','l2r')
% 'figure_only' specifies if only a figure window should be created; possible values:
% 'yes', 'no'.
% Default: {'figure_only','no'}
% 'figure' Specifies if new figure needs to be created or if the seismic
% traces should be plotted to the current axes of an existing
% figure. Possible values are 'new' and any other string.
% Default: {'figure','new'}
% 'fontsize' Size of the font for axis annotations, labels, and legends.
% Default: {'fontsize',11}
% 'interpol' 2-element cell array which specifies how data should be interpolated in time.
% Possible values are 'linear', 'cubic', and 'v5cubic'.
% 'cubic' - piecewise cubic Hermite interpolation
% 'v5cubic' - the cubic interpolation from MATLAB 5, which does not
% extrapolate and uses 'spline' if X is not equally spaced.
% Default: {'interpol','v5cubic'}
% 'orient' Plot orientation. Possible values are: 'portrait' and 'landscape'
% Default: {'orient','landscape'} for more than 10 traces
% {'orient','portrait'} for 10 or fewer traces
% 'peak_fill' 2-element cell array which specifies color of peak fill.
% Possible values are all permissible colors or the empty string.
% In the latter case, peaks are not filled.
% Default: {'peak_fill','black'}
% 'pixels' 2-element cell array. Minimum number of interpolation
% points to use for display. The greater the number the smoother
% the display if 'interpol' is 'cubic'.
% Default: {'pixels',500}
% 'polarity' 2-element cell array. Possible values are 1 and -1;
% Default: {'polarity',1}
% 'quality' 2-element cell array. Possible values are 'draft', 'high',
% and 'spikes'.
% Values 'draft' and 'high' display the data in form of wiggle traces.
% 'draft' quality (default) is faster and intended for screen
% and b/w hard copies;
% 'high' quality is for color hard copies (there is no visual
% difference between 'draft' and 'high' quality for
% screen displays and b/w copies).
% 'spikes' puts a spike at each sample location (intended
% for the didplay of reflection coefficients)
% Default: {'quality','draft'}
% 'scale' 2-element cell array which specifies if traces should be scaled individually.
% Possible values are 'yes', 'no', or the actual scale. This may be a scalar or a
% vector whose number of elements is equal to the number of traces.
% separation. The scale actually used must be obtained by specifying the output
% argument "aux".
% Default: {'scale','no'}
% 'spacing' 2-element cell array which specifies if traces should be
% equidistant ('equal') or non uniformly ('nonequal') spaced;
% in the latter case the header mnemonic used for annotation defines
% the trace-to-trace separation.
% Default: {'spacing','equal'}
% '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]}
% 'title' 2-element cell array consisting of the keyword 'title' and a title string;
% no title is plotted if the title string is empty.
% 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. A "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',''}
% 'trough_fill' 2-element cell array which specifies color of trough fill.
% Possible values are all permissible colors or the empty string.
% In the latter case troughs are not filled.
% Default: {'trough_fill',''}
% 'wiggle_color' 2-element cell array which specifies color of wiggles.
% Possible values are all permissible colors or the empty string.
% In the latter case wiggles are not plotted.
% Default: {'wiggle_color','black'}
% 'wiggle_width' line width of wiggles; default depends on the "quality
% factor"
% Default: {'wiggle_width',0.5} if the "quality" keyword is not
% "spikes"
% {'wiggle_width',max(0.25,125/number_of_samples)} if the
% "quality" keyword is "spikes"
%
% OUTPUT
% aux optional structure with scale factor(s) used (required if seismic
% data are to be plotted with the same scaling in different plots)
% 'scale' field with scale factor(s) used
% 'figure_handle' handle of the figure with the plot
%
% EXAMPLES
% seismic=s_data;
% aux=s_wplot(seismic,{'annotation','cdp'},{'direction','r2l'});
%
% % Display matrix as spikes (also used to show reflection coefficients)
% s_wplot(randn(100,3),{'quality','spikes'})
% UPDATE HISTORY
% September 1, 2007: bug fix in cursor tracking
% November 27, 2007: streamlined scale factor computation and annotation
% February 5, 2008: Fix bug in handling of certain null values
% March 30, 2008: Save handles of traces in output structure "aux"
% October 24, 2008: Add option to plot samples as spikes (to better
% display reflection coefficients; see keyword "quality")
% November 8, 2008: Make spike-width depend on number of samples;
% make the spike-display the default for matrix input
% January 19, 2009: Improve annotation of matrix display
% March 7, 2009: Make axes and axis annotations bold
% March 8, 2009: Make size of axis-related fonts an input parameter
% July 12, 2009: Reduce default of "wiggle_width" if parameter "quality"
% is 'spike'.
global S4M
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
%% Set default values
if isseismic
param.annotation='trace_no';
else
param.annotation='columns';
end
param.aindex=[];
param.background='white';
param.deflection=[];
param.direction='l2r';
param.doublebuffer='on';
param.figure='new';
param.figure_only='no';
param.first=1;
param.fontsize=11;
%param.inc=[];
%param.interactive=1;
param.interpol='v5cubic';
param.orient=[];
param.peak_fill='black';
param.pixels=800;
param.polarity=1;
param.quality='';
param.scale='no';
param.spacing='equal';
param.times=[];
param.title=strrep(seismic.name,'_','\_');
try
param.title(1)=upper(param.title(1));
catch
% do nothing
end
param.traces=[];
param.tracking='';
param.trough_fill='';
param.wiggle=''; % deprecated; replaced by 'wiggle_color'
param.wiggle_color='black';
param.wiggle_width=[];
% Replace defaults by actual input arguments
param=assign_input(param,varargin,'s_wplot');
%% Select requested subset of seismic data
if ~isempty(param.traces) || ~isempty(param.times)
seismic=select_subset_no1(seismic,param);
end
%% Check seismic input data to see if they can be plotted
[nsamp,ntr]=size(seismic.traces);
if nargout > 0
aux=[];
end
if nsamp <= 1
disp([' Only one sample per trace; "s_wplot" did not plot the dataset "',seismic.name,'".'])
return
elseif ntr == 0
disp([' Alert from "s_wplot": Data set "',seismic.name,'" has no traces to plot.'])
return
end
%% Set not-yet defined input parameters
if isseismic
param=set_undefined_parameters4seismic_no2(param,seismic,nsamp);
else
param=set_undefined_parameters4matrix_no3(param,seismic,nsamp);
end
if ~isempty(param.wiggle)
param.wiggle_color=param.wiggle;
end
%% Set indices of trace headers for annotation
if ntr < 21 && isempty(param.aindex)
if ntr < 11
param.aindex=1:ntr;
else
param.aindex=1:2:ntr;
end
end
if isempty(param.aindex)
indices=1:max([round(ntr/7),1]):ntr;
else
indices=param.aindex(param.aindex > 0 & param.aindex <= ntr);
end
%% Handle special cases of color for seismic traces
if strcmp(param.peak_fill,'gray')
param.peak_fill=[0.6,0.6,0.6];
elseif strcmp(param.peak_fill,'none')
param.peak_fill=[];
end
if strcmp(param.trough_fill,'gray')
param.trough_fill=[0.6,0.6,0.6];
elseif strcmp(param.trough_fill,'none')
param.trough_fill=[];
end
if strcmp(param.wiggle_color,'gray')
param.wiggle_color=[0.6,0.6,0.6];
elseif strcmp(param.wiggle_color,'none')
param.wiggle_color=[];
end
annotation=s_gh(seismic,param.annotation);
if ntr == 1 || isempty(annotation)
uniform=true;
annotlog=false;
else
ddd=diff(annotation);
annotlog=(max(ddd)==min(ddd)) && ddd(1) ~= 0 && isempty(param.aindex);
if annotlog
uniform=false;
else
if strcmp(param.spacing,'equal')
uniform=true; % Uniform trace-to-trace distance
else
uniform=false;
end
end
end
% Change polarity if requested
if param.polarity < 0
seismic.traces=-seismic.traces;
end
% Check if there are null values in the seismic data
isnullvalue=isnull(seismic);
% Interpolate data if necessary
if (strcmpi(param.interpol,'v5cubic') || strcmpi(param.interpol,'cubic')) && ...
nsamp < param.pixels && ~strcmp(param.quality,'spikes')
npix=round(param.pixels/(nsamp-1))*(nsamp-1);
times=linspace(seismic.first,seismic.last,npix)';
times_orig=linspace(seismic.first,seismic.last,nsamp)';
times=unique([times;times_orig]);
if isnullvalue && S4M.matlab_version >= 7 % Turn off warnings caused by NaN's in seismic traces
% warning('off','MATLAB:interp1:NaNinY')
yi=nan_interp1(times_orig,seismic.traces,times,param.interpol,0);
for ii=1:ntr % If necessary, replace last NaN at the top and
% first NaN at the bottom by zero to terminate
% patches
idx=find(~isnan(yi(:,ii)));
if ~isempty(idx)
if idx(1) > 1
if (yi(idx(1),ii) > 0 && ~isempty(param.peak_fill)) || ...
(yi(idx(1),ii) < 0 && ~isempty(param.trough_fill))
yi(idx(1)-1,ii)=0;
end
end
if idx(end) < nsamp
if (yi(idx(end,ii)) > 0 && ~isempty(param.peak_fill)) || ...
(yi(idx(end,ii)) < 0 && ~isempty(param.trough_fill))
yi(idx(end)+1,ii)=0;
end
end
end
end
% warning('on','MATLAB:interp1:NaNinY')
else
yi=interp1(seismic.first:seismic.step:seismic.last,seismic.traces,times,param.interpol);
end
else
% dti=seismic.step;
times=(seismic.first:seismic.step:seismic.last)';
yi=seismic.traces;
end
trace_max=max(abs(yi));
% Compute horizontal trace locations
if uniform
xi=1:ntr;
dx=1; % Trace-to-trace separation
else
xi=annotation;
dx=(max(xi)-min(xi))/(ntr-1+eps); % Trace-to-trace separation
end
% Scale data
if ischar(param.scale)
if strcmpi(param.scale,'yes')
scale=(dx*param.deflection)./(trace_max+eps)';
for ii=1:ntr
yi(:,ii)=yi(:,ii)*scale(ii);
end
else
scale=dx*param.deflection/(max(trace_max)+eps);
yi=yi*scale;
end
else
scale=param.scale;
if length(scale) == 1
yi=yi*scale;
elseif length(scale) == ntr
for ii=1:ntr
yi(:,ii)=yi(:,ii)*scale(ii);
end
else
error(' Scale factor must be a scalar or a vector of length equal to the number of traces')
end
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 scroll bars
wseismic_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);
if ~uniform
xi2use=xi;
else
xi2use=s_gh(seismic,param.annotation);
end
initiate_3d_tracking4seismic(options_menu_handle,seismic.traces*param.polarity, ...
xi2use,y,xinfo,yinfo,{'amplitude','','Amplitude'})
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
%% Handle background in axis area
ha=get(gcf,'CurrentAxes');
if ~strcmpi(param.background,'gray') && ~strcmpi(param.background,'grey')
try
set(ha,'Color',param.background)
catch %#ok
disp([' Probably illegal background color: "',param.background,'".'])
keyboard
end
else
bgGray
end
axis([min(xi)-dx*max([param.deflection,1]),max(xi)+dx*max([param.deflection,1]),seismic.first,seismic.last]);
hold on
set(ha,'ydir','reverse','XAxisLocation','top')
% Handle reversal of plot direction
if strcmpi(param.direction,'r2l')
set(ha,'xdir','reverse')
yi=-yi;
temp=param.trough_fill;
param.trough_fill=param.peak_fill;
param.peak_fill=temp;
elseif ~strcmpi(param.direction,'l2r')
error(['Keyword for plot direction is wrong (',param.direction,')'])
end
if strcmpi(param.figure_only,'yes')
return
end
% Plot data
switch param.quality
case 'draft'
handles=ue_seismic_plot(times,yi,xi,isnullvalue,param);
case 'high'
handles=ue_seismic_plot_ps(times,yi,xi,isnullvalue,param);
case 'spikes'
handles=ue_seismic_plot_spikes(times,yi,xi,isnullvalue,param);
otherwise
error(['Unknown value for keyword "quality": ',param.quality])
end
% Add annotation of horizontal axis
if ~annotlog
v=axis;
xil=xi(indices);
annol=annotation(indices);
add_xaxis([xil',annol'],'',{'location','top'});
end
% Add label of horizontal axis
% (if 5 or more traces or annotation other than trace number)
if ~strcmpi(param.annotation,'trace_no') || ntr > 4
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
hxlabel=xlabel(xtext);
v=get(hxlabel,'Position'); % Preserve position of x-axis label
else
hxlabel=xlabel('');
end
else
hxlabel=xlabel('');
set(gca,'XTickLabel',[])
end
if uniform && (~strcmpi(param.annotation,'trace_no') || ntr > 4)
% set(gca,'XTickLabel',[]); % Delete original annotation but
try % keep x-axis label at original position
set(hxlabel,'Position',v);
catch %#ok
end
end
set(ha,'gridlinestyle','-','box','on','xgrid','off','ygrid','on', ...
'FontSize',param.fontsize)
% Make axes, labels, etc. bold
make_axes_bold(ha)
% Title
if ~isempty(param.title)
if iscell(param.title) % Handle multi-line titles
mytitle(param.title{1})
else
mytitle(param.title)
end
end
zoom off
hold off
if nargout > 0
aux.figure_handle=figure_handle;
aux.scale=scale;
aux.handles=handles;
end
%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function handles=ue_seismic_plot(times,traces,location,isnullvalue,param)
% Function plot seismic traces at horizontal locations controlled by location
precision=class(traces);
if ~isempty(param.wiggle_color)
wiggle=true;
else
wiggle=false;
end
% dt=times(2)-times(1);
times_orig=times;
ntr=size(traces,2);
handles=zeros(ntr,3);
for ii=1:ntr
skip=false;
if isnullvalue
idx=find(~isnan(traces(:,ii)));
if isempty(idx)
skip=true;
else
y=traces(idx,ii);
times=times_orig(idx);
end
else
y=traces(:,ii);
end
if ~skip
chg=find(y(1:end-1).*y(2:end) < 0);
x_zero=abs(y(chg)./(y(chg+1)-y(chg))).*(times(chg+1)-times(chg))+times(chg);
[x_data,idx]=sort([times(1);times;x_zero;times(end)]);
y_data=[0;y;zeros(length(x_zero)+1,1,precision)];
y_data=y_data(idx);
if ~isempty(param.peak_fill);
pos=find(y_data >= 0);
handles(ii,1)=fill(y_data(pos)+location(ii),x_data(pos),param.peak_fill,'EdgeColor','none');
end
if ~isempty(param.trough_fill);
neg=find(y_data <= 0);
handles(ii,2)=fill(y_data(neg)+location(ii),x_data(neg),param.trough_fill,'EdgeColor','none');
end
if wiggle
handles(ii,3)=line(y_data(2:end-1)+location(ii),x_data(2:end-1),'Color',param.wiggle_color, ...
'EraseMode','none','LineWidth',param.wiggle_width);
end
end
end
%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function handles=ue_seismic_plot_ps(times,traces,location,isnullvalue,param)
% Function plots seismic traces at horizontal locations controlled by location
% Avoids vertical lines from top to bottom on some PS interpreters
% Much slower than ue_seismic_plot
precision=class(traces);
if ~isempty(param.wiggle_color)
wiggle=true;
else
wiggle=false;
end
times_orig=times;
ntr=size(traces,2);
handles=zeros(ntr,3);
for ii=1:ntr
skip=false;
if isnullvalue
idx=find(~isnan(traces(:,ii)));
if isempty(idx)
skip=true;
else
y=traces(idx,ii);
times=times_orig(idx);
end
else
y=traces(:,ii);
end
if ~skip
chg=find(y(1:end-1).*y(2:end) < 0);
x_zero=abs(y(chg)./(y(chg+1)-y(chg))).*(times(chg+1)-times(chg))+times(chg);
[x_data,idx]=sort([times(1);times;x_zero;times(end)]);
y_data=[0;y;zeros(length(x_zero),1,precision);0];
y_data=y_data(idx);
if ~isempty(param.peak_fill);
pos=find(y_data >= 0);
ind1=find(diff(pos) > 1);
ind=[pos(1),reshape([pos(ind1)';pos(ind1+1)'],1,2*length(ind1)),pos(end)];
for kk=1:2:length(ind)-1;
index=ind(kk):ind(kk+1);
handles(ii,1)=fill(y_data(index)+location(ii),x_data(index),param.peak_fill, ...
'erasemode','none','EdgeColor','none');
end
end
if ~isempty(param.trough_fill);
neg=find(y_data <= 0);
ind=find(diff(neg) > 1);
ind=[neg(1),reshape([neg(ind)';neg(ind+1)'],1,2*length(ind)),neg(end)];
for kk=1:2:length(ind)-1
index=ind(kk):ind(kk+1);
handles(ii,2)=fill(y_data(index)+location(ii),x_data(index),param.trough_fill, ...
'erasemode','none','EdgeColor','none');
end
end
if wiggle
handles(ii,3)=line(y_data(2:end-1)+location(ii),x_data(2:end-1),'Color',param.wiggle_color, ...
'erasemode','none','LineWidth',param.wiggle_width);
end
end
end
%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function handles=ue_seismic_plot_spikes(times,traces,location,isnullvalue,param)
% Function plot seismic traces at horizontal locations controlled by location
precision=class(traces);
timestimes=reshape([times';times';times'],[],1);
[nsamp,ntr]=size(traces);
zero=zeros(1,nsamp,precision);
nulls=NaN(1,nsamp,precision);
handles=zeros(ntr,2);
for ii=1:ntr
deflection=[traces(:,ii)';zero;nulls]+location(ii);
if ~isnullvalue || ~all(isnan(traces(:,ii)))
% Plot zero line
handles(ii,1)=line(0*traces(:,ii)+location(ii),times, ...
'Color',param.wiggle_color,'EraseMode','none','LineWidth',0.5);
% Plot spikes
handles(ii,2)=line(deflection(:),timestimes,'Color',param.wiggle_color, ...
'EraseMode','none','LineWidth',param.wiggle_width);
end
end
%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function seismic=select_subset_no1(seismic,param)
% Select requested subset of the seismic data
global S4M
history=S4M.history; % Preserve value of global variable S4M.history
S4M.history=false;
if isempty(param.times)
seismic=s_select(seismic,{'traces',param.traces});
elseif iscell(param.times)
seismic=s_select(seismic,{'traces',param.traces},{'null',NaN}, ...
{'times',param.times{1},param.times{2}});
else
seismic=s_select(seismic,{'traces',param.traces},{'null',NaN}, ...
{'times',param.times(1),param.times(2)});
end
S4M.history=history; % Restore history setting
%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function param=set_undefined_parameters4seismic_no2(param,seismic,nsamp)
% Set "quality" parameter if it is not an input argument
if isempty(param.quality)
param.quality='draft';
elseif strcmp(param.quality,'spikes')
param=set_undefined_parameters4matrix_no3(param,seismic,nsamp);
return
end
% Set "wiggle_width" parameter if it is not an input argument
if isempty(param.wiggle_width)
param.wiggle_width=0.5;
end
% Set "deflection" parameter and color if a seismic dataset is input
if isempty(param.deflection)
param.deflection=1.5;
end
%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function param=set_undefined_parameters4matrix_no3(param,seismic,nsamp)
% Set "quality" parameter if it is not an input argument
if isempty(param.quality)
param.quality='spikes';
end
% Set "wiggle_width" parameter if it is not an input argument
if isempty(param.wiggle_width)
param.wiggle_width=max(0.25,125/nsamp);
end
% Set "deflection" parameter and color if a matrix is input
if all(seismic.traces >= 0)
param.deflection=0.9;
else
param.deflection=0.6;
end
param.wiggle_color='red';
|
github
|
Abakumov/MLIB-master
|
s_iplot.m
|
.m
|
MLIB-master/OTHER/SeisLab_10.0301/S4M/Geophysics_3.0/s_iplot.m
| 20,350 |
utf_8
|
db452301f490276da1ebdf4d049ffe54
|
function aux=s_iplot(seismic,varargin)
% Function plots seismic data in wiggle-trace form.
% By default, positive deflections are filled black.
%
% Written by: E. Rietsch: April 15, 2000
% Last updated: March 16, 2007: set default for "scale" to 'no'; white background
%
% aux=s_iplot(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' 2-element or 3-element cell array. Defines a header
% mnemonic whose values are used to annotate the horizontal axis.
% Default: {'annotation','trace_no'}
% 'aindex annotation index; used to annotate specific traces with the
% value of the header selected via keyword annotation.
% EXAMPLE {'aindex',5:10:1000} every tenth trace annotated,
% starting with trace 5
% Default: {'aindex',[]} automatic annotation
% 'deflection' trace deflection in units of trace spacing.
% Default: ('deflection',1.25}
% 'direction' 2-element cell array defining plot direction. Possible
% values are: left-to-right, 'l2r', and right-to-left, 'r2l'.
% Default: {'direction','l2r')
% 'figure_only' specifies if only a figure window should be created;
% possible values: 'yes', 'no'.
% Default: {'figure_only','no'}
% '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'}
% 'interpol' 2-element cell array which specifies how data should be
% interpolated in time. Possible values are 'linear', 'cubic',
% and 'v5cubic'.
% 'cubic' - piecewise cubic Hermite interpolation
% 'v5cubic' - the cubic interpolation from MATLAB 5, which does not
% extrapolate and uses 'spline' if X is not equally spaced.
% Default: {'interpol','v5cubic'}
% 'orient' Plot orientation. Possible values are: 'portrait' and 'landscape'
% Default: {'orient','landscape'} for more than 10 traces
% {'orient','portrait'} for fewer than 11 traces
% 'peak_fill' 2-elementcell array which specifies color of peak fill. Possible values are
% all permissible colors or the empty string. In the latter case peaks are not filled.
% Default: {'peak_fill','k'}
% 'pixels' 2-element cell array. Minimum number of interpolation points to use for display.
% The greater the number the smoother the display if 'interpol' is 'cubic'.
% Default: {'pixels',200}
% 'polarity' 2-element cell array. Possible values are 1 and -1;
% Default: {'polarity',1}
% 'quality' 2-element cell array. Possible values are 'draft' and 'high'
% 'draft' quality (default) is faster and intended for screen and b/w hardcopies;
% 'high' quality is for color copies (there is no difference between
% 'draft' and 'high' quality for screen displays and b/w copies).
% Default: {'quality','draft'}
% 'scale' 2-element cell array which specifies if traces should be scaled individually.
% Possible values are 'yes', 'no', or the actual scale. This may be a scalar or a
% vector whose number of elements is equal to the number of traces.
% separation. The scale actually used must be obtained by specifying the output
% argument "aux".
% Default: {'scale','no'}
% 'spacing' 2-element cell array which specifies if traces should be
% equidistant ('equal') or nonuniformly ('nonequal') spaced;
% in the latter case the header mnemonic used for annotation defines
% the trace-to-trace separation.
% Default: {'spacing','equal'}
% '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]}
% 'title' 2-element cell array consisting of the keyword 'title' and a title string;
% no title is plotted if the title string is empty.
% Default: {'title',inputname(1)) where inputname(1) is the name of the seismic
% input data set
% '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. A "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 curor; possible values are 'yes' and 'no'
% Default: {'tracking','yes'} if parameter 'figure' == 'new'
% Default: {'tracking','no'} if parameter 'figure' == 'old'
% 'trough_fill' 2-element cell array which specifies color of trough fill.
% Possible values are all permissible colors or the empty string.
% In the latter case troughs are not filled.
% Default: {'trough_fill',''}
% 'wiggle_color' 2-element cell array which specifies color of wiggles.
% Possible values are all permissible colors or the empty string.
% In the latter case wiggles are not plotted.
% Default: {'wiggle_color','k'}
%
% OUTPUT
% aux optional structure with scale factor(s) used (required if seismic
% data are to be ploted with the same scaling in different plots)
% 'scale' field with scale factor(s) used
% 'figure_handle' handle of the figure with the plot
% EXAMPLE
% seismic=s_data;
% s_iplot(seismic,{'direction','r2l'},{'deflection',1})
global ABORTED
if ~istype(seismic,'seismic')
if isnumeric(seismic)
seismic=s_convert(seismic,1,1);
seismic.units='Samples';
else
error('First input argument must be seismic dataset or a matrix.')
end
end
aux=[];
ABORTED=false;
run_presets_if_needed
ntr=size(seismic.traces,2);
% Set default values
param.annotation='trace_no';
param.aindex=[];
param.background='white';
param.deflection=1.25;
param.direction='l2r';
param.doublebuffer='on';
param.figure='new';
param.figure_only='no';
param.first=1;
param.inc=[];
param.interactive=1;
param.interpol='v5cubic';
param.orient=[];
param.peak_fill='k';
param.pixels=500;
param.polarity=1;
param.quality='draft';
param.scale='no';
param.spacing='equal';
param.times=[];
param.title=seismic.name;
param.traces=[];
param.tracking=[];
param.trough_fill='none';
param.wiggle_color='k';
param.wiggle_width=0.5;
% Decode and assign input arguments
param=assign_input(param,varargin,'s_iplot');
% Create figure window (unless an existing figure is to be used)
if strcmpi(param.figure,'new')
if isempty(param.tracking)
param.tracking='yes';
end
if isempty(param.orient)
if ntr > 10
param.orient='landscape';
else
param.orient='portrait';
end
end
if strcmpi(param.orient,'landscape')
figure_handle=lfigure;
else
figure_handle=pfigure;
end
% figure_export_menu(figure_handle); % Create menu button to export figure as emf/eps file
set(figure_handle,'Color','w','DoubleBuffer',param.doublebuffer)
drawnow
wseismic_scrollbar_menu(figure_handle,seismic,param.direction) % Create scrollbars
else
figure_handle=gcf;
if isempty(param.tracking)
param.tracking='no';
end
end
% Handle background in axis area
if ~strcmpi(param.background,'gray') && ~strcmpi(param.background,'grey')
try
set(gca,'Color',param.background)
catch
disp([' Probably illegal background color: "',param.background,'".'])
end
else
bgGray
end
if nargout > 0
aux.figure_handle=figure_handle;
end
s_wplot_no1(seismic,param)
% Create structure "userdata" to save info that allows one to
% interactively modify the seismic plot
if param.interactive && strcmp(param.figure,'new')
haxis=gca;
userdata=get(figure_handle,'UserData');
userdata.seismic=seismic;
userdata.param=param;
userdata.axis_handle=haxis;
set(figure_handle,'UserData',userdata,'DoubleBuffer','on')
menu2edit_seismic(figure_handle) % Set menu button for plot parameters
end
if nargout == 0
clear aux
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function s_wplot_no1(seismic,param)
global ABORTED S4M
run_presets_if_needed
history=S4M.history; % Preserve value of global variable S4M.history
S4M.history=0;
if ~isempty(param.traces)
if ~iscell(param.traces)
seismic=s_select(seismic,{'traces',param.traces});
else
seismic=s_select(seismic,{'traces',param.traces{1},param.traces{2}});
end
% ntr=size(seismic.traces,2);
end
if ~isempty(param.times)
if length(param.times) <= 1
seismic=s_select(seismic,{'times',param.times});
elseif iscell(param.times)
seismic=s_select(seismic,{'times',param.times{1},param.times{2}});
else
seismic=s_select(seismic,{'times',param.times(1),param.times(2)});
end
% nsamp=size(seismic.traces,1);
end
S4M.history=history;
annotation=s_gh(seismic,param.annotation);
if length(annotation) == 1
uniform=true;
annotlog=false;
else
ddd=diff(annotation);
annotlog=(max(ddd)==min(ddd)) && ddd(1) ~= 0 && isempty(param.aindex);
if annotlog
uniform=false;
else
if strcmp(param.spacing,'equal')
uniform=true; % Uniform trace-to-trace distance
else
uniform=false;
end
end
end
[nsamp,ntr]=size(seismic.traces);
if nsamp*ntr == 0
disp([' Alert from "s_iplot": Data set "',seismic.name,'" has no traces to plot.'])
return
end
% Set indices of trace headers for annotation
if isempty(param.aindex)
indices=1:max([round(ntr/7),1]):ntr;
else
indices=param.aindex(param.aindex > 0 && param.aindex <= ntr);
end
if nsamp <= 1
ABORTED=true;
if param.interactive
msgdlg(' Only one sample per trace; seismic data set is not plotted.')
else
disp([' Only one sample per trace; "s_iplot" did not plot data set "',seismic.name,'"'])
end
return
end
% Change polarity if requested
if param.polarity < 0
seismic.traces=-seismic.traces;
end
% Interpolate data if necessary
if (strcmpi(param.interpol,'v5cubic') || strcmpi(param.interpol,'cubic')) && nsamp < param.pixels
if isnull(seismic)
for ii=1:ntr % Replace last NaN at the top and first NaN at the bottom by zero
idx=find(~isnan(seismic.traces(:,ii)));
if ~isempty(idx)
if idx(1) > 1
seismic.traces(idx(1)-1,ii)=0;
end
if idx(end) < nsamp
seismic.traces(idx(end)+1,ii)=0;
end
end
end
end
npix=round(param.pixels/(nsamp-1))*(nsamp-1);
dti=(seismic.last-seismic.first)/npix;
times=(seismic.first:dti:seismic.last)';
if isnull(seismic) && S4M.matlab_version >= 7 % 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;
times=(seismic.first:seismic.step:seismic.last)';
yi=seismic.traces;
end
trace_max=max(abs(yi));
% Compute horizontal trace locations
if uniform
xi=1:ntr;
else
xi=annotation;
if min(xi) == max(xi) && length(xi) > 1
disp([' Header requested for annotation ("',param.annotation,'") is constant;'])
disp(' please use uniform spacing')
error(' Abnormal termination')
end
end
% Trace-to-trace separation
if ntr > 1
dx=(max(xi)-min(xi))/(ntr-1);
else
dx=1;
end
% Scale data
if ischar(param.scale)
if strcmpi(param.scale,'yes')
scale=(dx*param.deflection)./(trace_max+eps)';
for ii=1:ntr
yi(:,ii)=yi(:,ii)*scale(ii);
end
% yi=yi*spdiags(scale,0,ntr,ntr);
else
scale=dx*param.deflection/(max(trace_max)+eps);
yi=yi*scale;
end
else
scale=param.scale;
if length(scale) == 1
yi=yi*scale;
elseif length(scale) == ntr
for ii=1:ntr
yi(:,ii)=yi(:,ii)*scale(ii);
end
% yi=yi*spdiags(scale(:),0,ntr,ntr);
else
error(' Scale factor must be scalar or vector of length equal to the number of traces')
end
end
if nargout == 1
aux.scale=scale;
end
% Create axis
axis([min(xi)-dx*max([param.deflection,1]),max(xi)+dx*max([param.deflection,1]),seismic.first,seismic.last]);
hold on
ha=get(gcf,'CurrentAxes');
set(ha,'ydir','reverse','XAxisLocation','top')
% Handle reversal of plot direction
if strcmpi(param.direction,'r2l')
set(ha,'XDir','reverse')
% dx=-dx;
yi=-yi;
temp=param.trough_fill;
param.trough_fill=param.peak_fill;
param.peak_fill=temp;
elseif strcmpi(param.direction,'l2r')
set(ha,'XDir','normal')
else
error(['Keyword for plot direction is wrong (',param.direction,')'])
end
if strcmpi(param.figure_only,'yes')
return
end
% Check if there are NaNs in the seismic data
if isnull(seismic)
isnull1=1;
else
isnull1=0;
end
% Plot data
if strcmpi(param.quality,'draft')
ue4i_seismic_plot(times,yi,xi,isnull1,param);
else
ue4i_seismic_plot_ps(times,yi,xi,isnull1,param)
end
box
if strcmpi(param.tracking,'yes')
% Add cursor tracking
[dummy,xinfo]=s_gh(seismic,param.annotation); %#ok First output argument is not required
y=linspace(seismic.first,seismic.last,nsamp);
yinfo=info4time(seismic);
initiate_3d_tracking4seismic(seismic.traces,xi,y,xinfo,yinfo,{'amplitude','','Amplitude'},ha)
end
% Add annotation of horizontal axis
if ~annotlog
v=axis;
xil=xi(indices);
annol=annotation(indices);
add_xaxis([xil',annol'],'',{'location','top'});
end
% Add label of horizontal axis
% (if 5 or more traces or annotation other than trace number)
if ~strcmpi(param.annotation,'trace_no') || ntr > 4
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
hxlabel=xlabel(xtext);
v=get(hxlabel,'Position'); % Preserve position of x-axis label
else
hxlabel=xlabel('');
end
else
set(gca,'XTickLabel',[])
end
if uniform && (~strcmpi(param.annotation,'trace_no') || ntr > 4)
% set(gca,'XTickLabel',[]); % Delete original annotation but
% keep x-axis label at original position
try
set(hxlabel,'Position',v);
catch
end
end
grid on;
set(ha,'gridlinestyle','-','box','on','xgrid','off')
% Title
if ~isempty(param.title)
if iscell(param.title) % Handle multi-line titles
mytitle(param.title{1})
else
mytitle(param.title)
end
end
zoom off
hold off
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function ue4i_seismic_plot(times,traces,location,isnull1,param)
% Function plot seismic traces at horizontal locations controlled by location
%
% INPUT
% times vector of y-coordinates for the trace samples
% traces matrix of trace samples
% location vector of x-coordinates of the traces
% isnull1 logical variable; true if the traces have null values.
% param structure with input parameters
dt=times(2)-times(1);
times_orig=times;
ntr=size(traces,2);
hpeak=zeros(1,ntr);
htrough=zeros(1,ntr);
hwiggle=zeros(1,ntr);
for ii=1:ntr
skip=0;
if isnull1
idx=find(~isnan(traces(:,ii)));
if isempty(idx)
skip=1;
else
y=traces(idx,ii);
times=times_orig(idx);
end
else
y=traces(:,ii);
end
if ~skip
chg=find(y(1:end-1).*y(2:end) < 0);
x_zero=abs(y(chg)./(y(chg+1)-y(chg)))*dt+times(chg);
[x_data,idx]=sort([times(1);times;x_zero;times(end)]);
y_data=[0;y;zeros(length(x_zero),1);0];
y_data=y_data(idx);
pos=find(y_data >= 0);
hpeak(ii)=fill(y_data(pos)+location(ii),x_data(pos),'w');
neg=find(y_data <= 0);
htrough(ii)=fill(y_data(neg)+location(ii),x_data(neg),'w');
if ~isempty(param.trough_fill) || ~isempty(param.peak_fill)
plot([location(ii),location(ii)],[times(2),times(end)],'w-')
end
hwiggle(ii)=line(y_data(2:end-1)+location(ii),x_data(2:end-1),'Color',param.wiggle, ...
'EraseMode','none','LineWidth',param.wiggle_width);
end
end
set(htrough,'EdgeColor','none','FaceColor',param.trough_fill)
set(hpeak,'EdgeColor','none','FaceColor',param.peak_fill)
bool=ishandle(hpeak);
hpeak=hpeak(bool);
htrough=htrough(bool);
hwiggle=hwiggle(bool);
set(hpeak,'FaceColor',param.peak_fill)
set(htrough,'FaceColor',param.trough_fill)
handles.hpeak=hpeak;
handles.htrough=htrough;
handles.hwiggle=hwiggle;
haxes=gca;
userdata=get(haxes,'UserData');
userdata.trace_handles=handles;
set(haxes,'UserData',userdata)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function ue4i_seismic_plot_ps(times,traces,location,isnull1,param)
% Function plot seismic traces at horizontal locations controlled by location
% Avoids vertical lines from top to bottom on some PS interpreters
% Much slower than ue_seismic_plot
dt=times(2)-times(1);
times_orig=times;
ipeak=0;
itrough=0;
[nsamp,ntr]=size(traces);
hpeak=zeros(1,nsamp*ntr);
htrough=zeros(1,nsamp*ntr);
hwiggle=zeros(1,ntr);
for ii=1:ntr
skip=0;
if isnull1
idx=find(~isnan(traces(:,ii)));
if isempty(idx)
skip=1;
else
y=traces(idx,ii);
times=times_orig(idx);
end
else
y=traces(:,ii);
end
if ~skip
chg=find(y(1:end-1).*y(2:end) < 0);
x_zero=abs(y(chg)./(y(chg+1)-y(chg))).*dt+times(chg);
[x_data,idx]=sort([times(1);times;x_zero;times(end)]);
y_data=[0;y;zeros(length(x_zero),1);0];
y_data=y_data(idx);
pos=find(y_data >= 0);
% y_pos=y_data(pos); pos=find(y_data >= 0);
ind1=find(diff(pos) > 1);
ind=[pos(1),reshape([pos(ind1)';pos(ind1+1)'],1,[]),pos(end)];
% x_pos=x_data(pos);
for kk=1:2:length(ind)-1;
index=ind(kk):ind(kk+1);
ipeak=ipeak+1;
hpeak(ipeak)=fill(y_data(index)+location(ii),x_data(index),'w', ...
'erasemode','none','EdgeColor','none');
end
neg=find(y_data <= 0);
ind=find(diff(neg) > 1);
ind=[neg(1),reshape([neg(ind)';neg(ind+1)'],1,[]),neg(end)];
% y_neg=y_data(neg);
% x_neg=x_data(neg);
for kk=1:2:length(ind)-1
itrough=itrough+1;
index=ind(kk):ind(kk+1);
htrough(itrough)=fill(y_data(index)+location(ii),x_data(index),'w', ...
'erasemode','none','EdgeColor','none');
end
hwiggle(ii)=line(y_data(2:end-1)+location(ii),x_data(2:end-1),'Color',param.wiggle, ...
'erasemode','none','LineWidth',param.wiggle_width);
end
end
hpeak=hpeak(1:ipeak);
htrough=htrough(1:itrough);
hwiggle=hwiggle(ishandle(hwiggle));
set(hpeak,'FaceColor',param.peak_fill)
set(htrough,'FaceColor',param.trough_fill)
handles.hpeak=hpeak;
handles.htrough=htrough;
handles.hwiggle=hwiggle;
haxes=gca;
userdata=get(haxes,'UserData');
userdata.trace_handles=handles;
set(haxes,'UserData',userdata)
|
github
|
Abakumov/MLIB-master
|
s_spectrum.m
|
.m
|
MLIB-master/OTHER/SeisLab_10.0301/S4M/Geophysics_3.0/s_spectrum.m
| 18,594 |
utf_8
|
85debd8ad7c3e2bc8d4de6d280a0dafc
|
function aux=s_spectrum(varargin)
% Display the spectrum of one or more seismic input data sets.
% Null values in any data set are replaced by zeros. A maximum of 100 curves
% can be displayed.
%
% Written by: E. Rietsch: July 3, 2000 (original version)
% Last updated: April 15, 2008: Add option to apply a taper window to the datset
%
% aux=s_spectrum{varargin}
% INPUT
% The first input parameters are seismic data sets (seismic data
% structures) or matrices; if they are matrices they are, internally,
% converted to seismic structures with units 'samples'.
% It is important that all seismic input data sets have the same units.
% The seismic data sets may be followed by cell arrays which consist of a
% keyword and one or more parameters
% seis1 seismic structure or matrix
% seis2 seismic structure or matrix
% ...
% seisn seismic structure or matrix
%
% parameters one or more cell arrays; the first element of each cell array is
% a keyword, the other elements are parameters.
% Presently, keywords are:
% 'average' Possible values are 'yes' (or true) or 'no' (or false).
% Only relevant for multi-trace datasets.
% If {'average',true} then the average spectrum of the traces is
% computed and displayed;
% if {'average',false} the spectra of the individual traces
% are computed and displayed
% Default: {'average',true}
% 'colors' Colors to be used for consecutive curves.
% Possible values: any permissible color and line style combinations;
% if there are more datasets than colors/line styles (default 21) the
% colors/line styles will be repeated
% Default: {'colors','r','b','g','m','k','c','y',...
% 'r--','b--','g--','m--','k--','c--','y--' ...
% 'r:','b:','g:','m:','k:','c:','y:'};
% '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'}
% 'frequencies' Two positive numbers representing the range of frequencies to
% display. The first number must be non-negative and smaller than
% the second. If the second number is greater than the Nyquist
% frequency of the data set with the smallest sample interval, it
% is set to the Nyquist frequency.
% Default: {'frequencies',0,inf}
% 'legend' Figure legend (curve annotation).
% Default: names of the seismic input data sets.
% 'lloc' Location of figure legend. For possible values see: help legend
% Default: {'lloc','best'}
% 'linewidth' Line width of curves. Default: {'linewidth',2}
% 'orient' Plot orientation. Possible values are: 'portrait' and 'landscape'
% Default: {'orient','landscape'}
% 'plot' Types of plot(s) to create. Possible values are:
% 'amp' plot amplitude spectrum
% 'phase' plot phase spectrum
% 'both' plot amplitude and phase spectrum
% Default: {'plot','amp'} ... plot amplitude spectrum only
% 'padding' Traces with fewer than "padding" samples are padded with
% zeros. This parameter is ignored if the number of samples
% per trace exceeds "padding".
% Default:{'padding',256}
%
% Keywords relevant for amplitude spectrum only:
% 'normalize' Establish if or how the amplitude spectra are to be
% normalized.
% Possible values are:
% 'amplitude' scale data so that the mean spectral amplitude is
% the same
% 'peak' scale spectra so that their peaks are the same
% 'power' scale spectra so that the area under the power spectrum
% is the same for all signals.
% 'no' do not scale spectra
% Default: {'normalize','power'}
% The "normalize" parameter is ignored if the scale parameter
% (see below) is 'dB'.
% 'scale' Set the scale of the y-axis. Possible values are:
% 'linear' plot amplitude spectrum
% 'power' plot power spectrum
% 'log' power spectrum in logarithmic scale
% 'dB' power spectrum in dB. (the parameter value is not case
% sensitive; 'db' or 'DB' are also allowed)
% Default: {'scale','linear'}
%
% Keywords relevant for phase spectrum only:
% 'tiepoint' since the phase is only determined up to a multiple of 2*pi
% (360 degrees) this parameter specifies where the phase is forced
% to be in the range of (-180,180]. For arbitrary wavelets this is
% usually the dominant frequency (e.g. the term 60-degree wavelet)
% For a minimum-phase wavelet one would prefer DC (zero frequency).
% Hence "tiepoint" has two values "zero' and 'peak'.
% Default: {'tiepoint','peak'}
% 'timezero' Zero-time used for phase calculation. Possible values
% are 'best' and 'actual'.
% 'actual': The actual time zero of a dataset (e.g.seismic.first)
% is used to compute the phase. In this case the phase may
% include a linear component
% 'best': The dataset is shifted so that time zero is a
% the peak of its Hilbert transform. There is no linear
% component.
% Default: {'timezero','best'}
% 'window' string with name of taper window; see function "s_window" for
% possible values.
% Default: {'window','none'}
% OUTPUT
% aux Structure
% 'figure_handle' handle to figure
% 'handles4amp' handle of the axes for the amplitude spectrum (if any)
% 'handles4phase' handle of the axes for the phase spectrum (if any)
%
% EXAMPLES
% wavelet=-s_create_wavelet({'type','min-phase'});
% s_spectrum(wavelet,{'plot','amp'},{'frequencies',0,80},{'padding',128})
%
% lfigure
% subplot(1,2,1)
% s_spectrum(wavelet,{'plot','phase'},{'timezero','best'},{'figure','old'})
% mytitle('best')
% subplot(1,2,2)
% s_spectrum(wavelet,{'plot','phase'},{'timezero','actual'},{'figure','old'})
% mytitle('actual')
% mysuptitle('Two options for phase plot using parameter "timezero"',{'color','blue'})
%
% seismic=s_data;
% s_spectrum(seismic,wavelet,{'scale','log'})
% UPDATE HISTORY
% October 16, 2007: Use TeX-style text in legend
% December 21, 2007: remove restrictions
% January 21, 2008: preserve DC component
% Find number of input seismic data sets or matrices; convert matrices
% to seismic datasets
nseis=nargin;
types=true(1,nseis);
for ii=1:nargin
if iscell(varargin{ii})
nseis=ii-1;
break
else
if isstruct(varargin{ii})
% Do nothing
elseif isnumeric(varargin{ii})
varargin{ii}=s_convert(varargin{ii},1,1,' ','samples');
varargin{ii}.name=['# ',num2str(ii)];
types(ii)=false;
else
error('Input arguments must be structures, numeric arrays or cell arrays.')
end
end
end
if nseis == 0
error(' At least the first input argument must be a seismic data set or a matrix.')
end
% Check if input datasets are either all matrices or seismic datasets
% (no mixing of the two)
isseismic=all(types(1:nseis));
ismatrix=all(~types(1:nseis));
if ~isseismic && ~ismatrix
error('Seismic datasets and matrices cannot be mixed.')
end
% Create cell array with datasets whose spectra are to be plotted
maxcurves=1000;
datasets=cell(1,maxcurves);
number_of_traces=zeros(1,maxcurves);
steps=zeros(1,maxcurves);
ik=0;
for ii=1:nseis
lds=length(varargin{ii});
if lds > 1
for jj=1:lds
ik=ik+1;
temp=varargin{ii}(jj);
temp.name=[temp.name,' (',num2str(jj),')']; % Create distinctive name for plot label
number_of_traces(ik)=size(temp.traces,2);
steps(ii)=temp.step;
datasets{ik}=temp;
end
else
ik=ik+1;
datasets{ik}=varargin{ii};
steps(ik)=datasets{ik}.step;
number_of_traces(ik)=size(datasets{ik}.traces,2);
end
end
steps(ik+1:end)=[];
datasets(ik+1:end)=[];
param.steps=steps(1:ik); % Sample intervals for all input datasets
number_of_traces(ik+1:end)=[];
total_number_of_traces=sum(number_of_traces);
if ik > maxcurves
disp([' Spectra of ',num2str(ik),' datasets requested.'])
disp([' The maximum number of individual spectra is ',num2str(maxcurves),'.'])
error('Abnormal termination.')
end
% Define defaults for parameters
param.average=true;
param.bestshift='true';
param.colors={'r','b','g','k','c','m','y', ...
'r--','b--','g--','k--','c--','m--','y--', ...
'r:','b:','g:','k:','c:','m:','y:'};
param.figure='new';
param.legend=[];
param.lloc='best';
param.linestyle='-';
param.linewidth=2;
param.normalize='power';
param.frequencies={0,inf};
param.padding=256;
param.option='average';
param.orient='landscape';
param.plot='amp';
param.scale='linear';
param.single=''; % Deprecated
param.tiepoint='peak';
param.timezero='best';
param.window='none';
% Replace defaults by actual input arguments
if nseis < nargin
param=assign_input(param,{varargin{nseis+1:nargin}});
end
if ~isempty(param.single)
alert('Parameter "single" is obsolete: please use parameter "average" instead.')
param.average=~isyes(param.single);
end
% Convert input data to one-trace datasets if no averaging is requested
if ~isyes(param.average)
if total_number_of_traces > maxcurves
disp([' Individual spectra of ',num2str(total_number_of_traces),' traces requested.'])
disp([' The maximum number of individual spectra computed is ',num2str(maxcurves),'.'])
error('Abnormal termination.')
end
if total_number_of_traces > ik
ie=cumsum(number_of_traces);
ia=[1,ie(1:end-1)+1];
for ii=length(ia):-1:1
temp=s_ds2dsvector(datasets{ii});
if length(temp) == 1
datasets{ia(ii)}=temp;
else
ik=0;
for jj=ia(ii):ie(ii)
ik=ik+1;
temp(ik).name=[temp(ik).name,' ',num2str(ik)];
datasets{jj}=temp(ik);
end
end
end
end
nseis=total_number_of_traces;
else
nseis=ik;
end
% Prepare input arguments for actual use
if ~iscell(param.colors)
param.colors={param.colors};
end
[param.colors,param.linestyles]=split_colors_linestyles(param.colors);
% Define frequency range to plot
if isinf(param.frequencies{2})
param.frequencies{2}=500/min(steps);
end
if param.frequencies{1} < 0;
param.frequencies{1}=0;
end
if param.frequencies{1} >= param.frequencies{2}
error([' Incompatible spectrum frequencies: ', ...
num2str(param.frequencies{1}),' ',num2str(param.frequencies{2})])
end
% Create/get figure window
if strcmpi(param.figure,'new')
if strcmpi(param.orient,'landscape')
figure_handle=lfigure;
else
figure_handle=pfigure;
end
else
figure_handle=gcf;
end
ltext=cell(nseis,1); % Reserve room for legend
% Units of x-axis
param.xunits=units2frequencydomain(datasets{1}.units);
param.label4x=['Frequency (',param.xunits,')'];
switch param.plot
case 'amp'
handle4amp_axis=gca;
if strcmpi(param.scale,'log')
set(handle4amp_axis,'Yscale','log')
end
for ii=1:nseis
ltext{ii}=mnem2tex(datasets{ii}.name);
plot_amplitude_spectrum_no1(s_rm_trace_nulls(datasets{ii}),param,ii);
end
finish_amplitude_plot_no3(param,ltext)
case 'phase'
handle4phase_axis=gca;
for ii=1:nseis
plot_phase_spectrum_no2(s_rm_trace_nulls(datasets{ii}),param,ii);
ltext{ii}=mnem2tex(datasets{ii}.name);
end
finish_phase_plot_no4(param,ltext)
case 'both'
if ~strcmpi(param.figure,'new')
error('If amplitude and phase are to be plotted the figure parameter must be set to ''new''.')
end
% Create subplot axes
if strcmpi(param.orient,'portrait')
handle4amp_axis=subplot(2,1,1);
handle4phase_axis=subplot(2,1,2);
else
handle4amp_axis=subplot(1,2,1);
handle4phase_axis=subplot(1,2,2);
end
for ii=1:nseis
ltext{ii}=mnem2tex(datasets{ii}.name);
axes(handle4amp_axis)
plot_amplitude_spectrum_no1(s_rm_trace_nulls(datasets{ii}),param,ii);
axes(handle4phase_axis)
plot_phase_spectrum_no2(s_rm_trace_nulls(datasets{ii}),param,ii);
end
finish_phase_plot_no4(param,ltext)
axes(handle4amp_axis)
finish_amplitude_plot_no3(param,ltext)
% Link the frequency axes of the two plots
linkaxes([handle4amp_axis,handle4phase_axis],'x')
%{
if nargout > 0
aux.zoom_handles=disable_zoom(figure_handle);
else
disable_zoom(figure_handle)
end
%}
otherwise
error(['Unknown plot option: "',param.plot,'".'])
end
if nargout > 0
aux.figure_handle=figure_handle;
try
aux.handle4amp_axis=handle4amp_axis;
catch %#ok
end
try
aux.handle4phase_axis=handle4phase_axis;
catch %#ok
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function aux=plot_amplitude_spectrum_no1(dataset,param,index)
% Plot amplitude spectrum
% Apply taper window if required
switch param.window
case {'none','rect'}
% Do nothing
otherwise
dataset=s_window(dataset,param.window);
end
% Compute FFT and amplitude spectrum
nsamp=size(dataset.traces,1);
nfft=max(nsamp,param.padding);
ftseis=fft(dataset.traces,nfft);
% Compute frequencies values
if mod(nfft,2) == 0
nffth=nfft/2+1;
else
nffth=(nfft+1)/2;
end
ftseis(nffth+1:end,:)=[];
aftseis=mean(abs(ftseis),2)/nfft;
% Normalize the spectra (if requested)
switch param.normalize
case 'peak'
aftseis=aftseis/max(aftseis);
case 'power'
aftseis=aftseis/norm(aftseis);
case 'amplitude'
aftseis=aftseis/mean(aftseis);
case 'no'
% Do nothing
otherwise
disp(['Alert from S_SPECTRUM: Unknown normalization parameter: "',param.normalize,'". Spectrum is not normalized.'])
end
% Set the scale to be plotted
switch lower(param.scale)
case {'power','log'}
aftseis=aftseis.^2;
otherwise
% do nothing
end
% Set the scale to be plotted
%aftseis(1)=0;
switch lower(param.scale)
case 'log'
aftseis=max(aftseis,eps*max(aftseis));
case 'db'
aftseis=max(aftseis,eps*max(aftseis));
aftseis=20*log10(aftseis);
aftseis=aftseis-max(aftseis);
otherwise
% do nothing
end
% Determine abscissa values
nyquist=500/dataset.step;
freq=(0:2:nfft)*nyquist/nfft;
bool=freq >= param.frequencies{1} & freq <= param.frequencies{2};
freq=freq(bool);
aftseis=aftseis(bool);
% Plot amplitude spectrum
idx=mod(index-1,length(param.linestyles))+1;
line(freq,aftseis,'LineWidth',param.linewidth,'Color',param.colors{idx}, ...
'LineStyle',param.linestyles{idx});
if nargout > 0
aux.ftseis=ftseis;
aux.freq=freq;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function aux=plot_phase_spectrum_no2(dataset,param,index)
% Plot phase spectrum
[nsamp,ntr]=size(dataset.traces);
nfft=max(param.padding,nsamp);
switch param.timezero
case 'best'
timezero=[];
case 'actual'
timezero=dataset.first;
otherwise
error(['Unknown value of parameter "timezero": ',param.timezero])
end
if ntr > 1
for ii=1:ntr
[phase,aux]=signal_phase_spectrum(dataset.traces(:,ii),nfft, ...
timezero,param.tiepoint);
if ii==1;
avphase=phase;
else
avphase=avphase+phase;
end
end
phase=avphase/ntr;
else
[phase,aux]=signal_phase_spectrum(dataset.traces,nfft, ...
timezero,param.tiepoint);
end
% Determine abscissa values
nyquist=500/dataset.step;
freq=aux.freq*nyquist;
%freq=(0:2:nfft)*nyquist/nfft;
bool=freq >= param.frequencies{1} & freq <= param.frequencies{2};
freq=freq(bool);
phase=phase(bool);
ik=true;
while all(phase < 0) && any(phase < 180)
phase=phase+360;
ik=false;
end
if ik
while all(phase > 0) && any(phase > 180)
phase=phase-360;
end
end
% Plot phase spectrum
idx=mod(index-1,length(param.linestyles))+1;
line(freq,phase,'LineWidth',param.linewidth,'Color',param.colors{idx}, ...
'LineStyle',param.linestyles{idx});
if nargout > 0
aux.phase=phase;
aux.freq=freq;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function finish_amplitude_plot_no3(param,ltext)
% Create axis labels
xlabel(param.label4x)
switch lower(param.scale)
case 'linear'
switch lower(param.normalize)
case {'peak','power'}
label4y='Normalized spectral amplitude';
otherwise
label4y='Spectral amplitude';
end
case 'power'
switch lower(param.normalize)
case {'peak','power'}
label4y='Normalized spectral power';
otherwise
label4y='Spectral power';
end
case 'log'
switch lower(param.normalize)
case {'peak','power'}
label4y='Normalized spectral power';
otherwise
label4y='Spectral power';
end
case 'db'
switch lower(param.normalize)
case {'peak','power'}
label4y='Normalized spectral power (dB)';
otherwise
label4y='Spectral power (dB)';
end
otherwise
label4y='';
end
%{
switch param.normalize
case 'peak'
label4y=[label4y,' (normalized peak amplitude)'];
case 'power'
label4y=[label4y,' (normalized energy)'];
otherwise
% do nothing
end
%}
ylabel(label4y)
grid on
box on
bgGray
axis tight
legend(ltext,'Location',param.lloc)
initiate_2d_tracking({'Freq.',param.xunits,'Frequency'},{'Amp.','n/a','Amplitude'})
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function finish_phase_plot_no4(param,ltext)
% Create axis labels
xlabel(param.label4x)
if isempty(param.timezero)
ylabel('Phase in degrees (zero-time at peak of Hilbert transform)')
else
ylabel('Phase in degrees')
end
grid on
box on
bgGray
axis tight
legend(ltext,'Location',param.lloc)
initiate_2d_tracking({'Freq.',param.xunits,'Frequency'},{'Phase.','degrees','Phase'})
|
github
|
Abakumov/MLIB-master
|
s_stack_with_deviation.m
|
.m
|
MLIB-master/OTHER/SeisLab_10.0301/S4M/Geophysics_3.0/s_stack_with_deviation.m
| 4,480 |
utf_8
|
a2b8c62be61146570e11ef682cc73c71
|
function [stack,deviation,aux]=s_stack_with_deviation(seismic,varargin)
% Compute stack and the deviation of each input trace from the stack.
% Thus "deviation" has as many traces as "seismic"; each trace is the
% difference between the corresponding trace of seismic and the stacked
% trace associated with it.
% A scaling option allows one to compute the difference
% "seismic.trace - a*stack.trace"
% where "a" is a scale factor chosen internally to make the difference small in the
% least-squares sense.
%
% Written by: E. Rietsch: April 3, 2006
% Last updated:
%
% [stack,deviation,aux]=s_stack_with_deviation(seismic,varargin)
% INPUT
% seismic seismic dataset (for meaningful results it should have more
% than one trace)
% 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.
% 'scaling' possible values are 'yes' and 'no';
% if scaling is 'yes' a scaling factor is computed and applied
% to the stack trace prior to subtraction. This reduced the
% traces of "deviation" in particular if trace amplitude is a
% a major source of the difference between a seismic trace and
% the associated stack.
% Default: {'scaling','no'}
% OUTPUT
% stack seismic structure with the stacked data
% headers are averaged as well
% aux structure with additional data
% 'multi' 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".
% 'stdeviation' standard deviation of seismic traces from associated
% stack (i.e. of "seismic.trace - a*stack.trace")
% Set defaults for input parameters
param.header='';
param.scaling='no';
% Replace input arguments by actual ones
param=assign_input(param,varargin);
[stack,aux]=s_stack(seismic,{'header',param.header});
deviation=seismic;
switch param.scaling
case 'no'
[deviation.traces,stdev]=deviation_no1(seismic,stack,param);
case 'yes'
[deviation.traces,stdev]=deviation_no2(seismic,stack,param);
otherwise
error(['Unknown scaling option: ',param.scaling])
end
if nargout > 2
stdeviation=stack;
stdeviation.traces=stdev;
aux.stdeviation=stdeviation;
end
% Create history
deviation=s_history(deviation,'append');
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [traces,stdev]=deviation_no1(seismic,stack,param)
% Compute deviation without scaling of stack trace(s)
traces=zeros(size(seismic.traces));
if ~isempty(param.header)
uh=s_gh(stack,param.header);
headers=s_gh(seismic,param.header);
stdev=zeros(size(stack.traces));
for ii=1:length(uh)
index=find(headers==uh(ii));
for jj=1:length(index)
traces(:,index(jj))=seismic.traces(:,index(jj))-stack.traces(:,ii);
end
stdev(:,ii)=std(traces(:,index),1,2);
end
else
for ii=1:size(seismic.traces,2)
traces(:,ii)=seismic.traces(:,ii)-stack.traces;
end
stdev=std(traces,1,2);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [traces,stdev]=deviation_no2(seismic,stack,param)
% Compute deviation with scaling of stack trace(s)
traces=zeros(size(seismic.traces));
stdev=zeros(size(seismic.traces));
if ~isempty(param.header)
uh=s_gh(stack,param.header);
headers=s_gh(seismic,param.header);
for ii=1:length(uh)
index=find(headers==uh(ii));
for jj=1:length(index)
temp=seismic.traces(:,index(jj));
bool=~isnan(temp);
a=(temp(bool)'*stack.traces(bool,ii))/norm(stack.traces(bool,ii))^2;
traces(:,index(jj))=seismic.traces(:,index(jj))-a*stack.traces(:,ii);
end
stdev(:,ii)=std(traces(:,index),1,2);
end
else
for ii=1:size(seismic.traces,2)
temp=seismic.traces(:,ii);
bool=~isnan(temp);
a=(temp(bool)'*stack.traces(bool))/norm(stack.traces(bool))^2;
traces(:,ii)=seismic.traces(:,ii)-a*stack.traces;
end
stdev=std(traces,1,2);
end
|
github
|
Abakumov/MLIB-master
|
l_select.m
|
.m
|
MLIB-master/OTHER/SeisLab_10.0301/S4M/Geophysics_3.0/l_select.m
| 5,255 |
utf_8
|
b3057b69e9d230312fddf623d8ea6665
|
function wlog=l_select(wlog,varargin)
% Function retrieves subset of well log from a log structure.
% If wlog is a structure vector the same subset is selected from each well log.
% An error message is printed if a column mnemonic requested is not found.
% Column mnemonics are not case sensitive.
%
% Written by: E. Rietsch: October 7, 2000;
% Last updated: September 19, 2007: allow "wlog" to be a structure vector
%
% wlog=l_select(wlog,varargin)
% INPUT
% wlog well-log 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:
% 'curves' strings with curve mnemonics.
% Default: {'curves','*'} (implies all curves)
% The depth (first column of "wlog.curves") is always included
% 'depths' start and end depth of log segment (two comma-separated numbers
% or a two-element vector)
% Default: {'depths',wlog.first,wlog.last}
% 'rows' string with logical expression involving one more of the
% curve mnemonics
% Default: {'rows',''} (implies all rows)
% Keywords 'curves', 'depths', and 'rows' may be given at the same time
%
% OUTPUT
% wlog output log with curves defined in "curves"
%
% EXAMPLES
% wlog=l_data;
% wlog1=l_select(wlog,{'curves','Vp'},{'rows','depth >= 9000'})
% wlog2=l_select(wlog,{'curves','depth','Vp','Vs'},{'depths',10000,12000})
% wlog3=l_select(wlog,{'rows','depth >= 9000 & Vp < 7000'})
% wlog4=l_select(wlog,{'depths',7500,12000},{'rows','vclay < 0.35'})
% Set default values for input arguments
param.curves='*';
param.depths=[wlog(1).first,wlog(1).last];
param.rows='';
% Replace defaults by actual input arguments
param=assign_input(param,varargin);
if iscell(param.depths)
param.depths=cell2mat(param.depths);
end
lwlog=length(wlog);
if lwlog == 1
wlog=l_select_no1(wlog,param);
else
for ii=lwlog:-1:1
temp(ii)=l_select_no1(wlog(ii),param); %#ok Loop starts with highest index
end
wlog=temp;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function wlog=l_select_no1(wlog,param)
global S4M
ncols=size(wlog.curves,2);
% Select curves
if strcmp(param.curves,'*')
cindex=1:ncols;
else
cindex=curve_indices(wlog,param.curves);
if isempty(cindex) || any(cindex==0)
error(' No log curves selected. Abnormal termination.')
end
if cindex(1) ~= 1
cindex=[1,cindex];
end
end
% Select rows
param.depths=sort(param.depths);
dindex=find(wlog.curves(:,1) >= param.depths(1) & wlog.curves(:,1) <= param.depths(2));
if isempty(dindex)
error([' Requested depth range (',num2str(param.depths(1)),', ',num2str(param.depths(2)), ...
') outside of range of log depths (',num2str(wlog.first),', ',num2str(wlog.last),')'])
end
if ~isempty(param.rows)
% Find all the words in the logical expression
words=lower(extract_words(param.rows));
mnems=wlog.curve_info(ismember(lower(wlog.curve_info(:,1)),words),1); % Find curve mnemonics in logical expression
index=curve_indices(wlog,mnems,0);
index=unique(index);
index=index(index > 0);
if isempty(index)
disp([' There are no curve mnemonics in logical expression "',param.rows,'"'])
error([' Available curve mnemonics are: ',cell2str(wlog.curve_info(:,1))])
end
% Create vectors whose names are the curve mnemonics in the logical expression
for ii=1:length(index)
eval([lower(char(wlog.curve_info(index(ii),1))),' = wlog.curves(dindex,index(ii));']);
end
% Modify expression to be valid for vectors
expr=strrep(param.rows,'*','.*');
expr=strrep(expr,'/','./');
expr=strrep(expr,'^','.^');
expr=lower(expr);
% Evaluate modified expression
try
rindex=eval(['find(',expr,')']);
catch %#ok
disp([' Expression "',param.rows,'" appears to have errors.'])
disp([' Curve mnemonics found in expression: ',cell2str(wlog.curve_info(index,1))])
disp([' Curve mnemonics available: ',cell2str(wlog.curve_info(:,1))])
disp(' Misspelled curve mnemonics would be interpreted as variables.')
error(' Abnormal termination')
end
if isempty(rindex)
error([' No rows selected by condition "',param.rows,'"'])
else
dindex=dindex(rindex);
end
end
wlog.curve_info=wlog.curve_info(cindex,:);
wlog.curves=wlog.curves(dindex,cindex);
wlog.first=wlog.curves(1,1);
wlog.last=wlog.curves(end,1);
wlog.step=depths2step(wlog.curves(:,1));
% Add null value if necessary
if isnull(wlog.null) && any(any(isnan(wlog.curves(:,2:end))))
wlog.null=[];
end
% Select subset of curve types including only those curves that are
% also in the log
if isfield(wlog,'curve_types') && ~isempty(wlog.curve_types)
if S4M.case_sensitive
bool=ismember(wlog.curve_types(:,1),wlog.curve_info(:,1));
else
bool=ismember(lower(wlog.curve_types(:,1)),lower(wlog.curve_info(:,1)));
end
if ~any(bool)
wlog=rmfield(wlog,'curve_types');
else
wlog.curve_types=wlog.curve_types(bool,:);
end
end
|
github
|
Abakumov/MLIB-master
|
ds_unit_conversion.m
|
.m
|
MLIB-master/OTHER/SeisLab_10.0301/S4M/Geophysics_3.0/ds_unit_conversion.m
| 13,271 |
utf_8
|
89360b07c8bfcd0d3b00d454f1b8ac59
|
function dataset=ds_unit_conversion(dataset,varargin)
% Function converts units of measurements of columns/curves/headers/panels and
% parameters in a dataset structure.
% Datasets supported are: seismic data, well logs, tables,and pseudo-wells.
% Units of measurement for the time/depth axis are also modified for well logs
% and pseudo-wells.
%
% Written by: E. Rietsch: December 10, 2007
% Last updated:
%
% dataset=ds_unit_conversion(dataset,varargin)
% INPUT
% dataset log structure or table 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
% dataset dataset structure with new units of measurement
%
% EXAMPLES
% % Change 'ft' to 'm' and '%' to 'fraction'
% wlog=l_data;
% wlog=ds_unit_conversion(wlog,{'ft','m'},{'%','fraction'});
% l_curve(wlog)
%
% % Change 'ft/s' to 'm/s' (but only for Vs)
% wlog=ds_unit_conversion(wlog,{'ft/s','m/s','Vs'});
% l_curve(wlog)
%
% % Change units of measurement in a seismic header
% seismic=ds_add_header(s_data,100,{'offset','m','Offset'});
% ds_header(seismic)
% seismic=ds_unit_conversion(seismic,{'m','ft'});
% ds_header(seismic)
global S4M
ier=0;
for kk=1:length(dataset)
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 ==> %
[dataset,ier]=unit_conversion(dataset,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
dataset=unit_conversion(dataset,units,'new=old*0.3048');
[dataset,ier]=unit_conversion(dataset,{'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
[dataset,ier]=unit_conversion(dataset,units,'new=old*8.35');
elseif strcmp(units{2},'kg/m3') % g/cm3 ==> kg/m3
[dataset,ier]=unit_conversion(dataset,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
[dataset,ier]=unit_conversion(dataset,units,'new=old*0.00835');
elseif strcmp(units{2},'g/cm3') % kg/m3 ==> g/cm3
[dataset,ier]=unit_conversion(dataset,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
dataset=unit_conversion(dataset,units,'new=old/0.3048');
[dataset,ier]=unit_conversion(dataset,{'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
[dataset,ier]=unit_conversion(dataset,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
[dataset,ier]=unit_conversion(dataset,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
[dataset,ier]=unit_conversion(dataset,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
[dataset,ier]=unit_conversion(dataset,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
[dataset,ier]=unit_conversion(dataset,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
[dataset,ier]=unit_conversion(dataset,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
[dataset,ier]=unit_conversion(dataset,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
% Only insignificant warnings
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [dataset,ier]=unit_conversion(dataset,units,expression)
% Function converts values of one or more curves with the same units of
% measurement using the relationship in input argument "expression"
% INPUT
% dataset 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
% dataset log structure with the updated curve(s)
% ier error code: no error ==> ier = false
% error ==> ier = true
% An "error" occurs if no column/curve/panel/header/ with specified
% units of measurement is found or if curve mnemonics are specified
% ("units" has more than 2 elements) but are not fund in dataset
% An ALERT message is printed if ier is true and global variable
% S4M.alert == 1
switch dataset.type
case 'well_log'
[dataset,ier]=convert4log_and_table_no2(dataset,units,expression,'curve_info','curves');
case 'table'
% dataset=t_loose2compact(dataset);
[dataset,ier]=convert4log_and_table_no2(t_loose2compact(dataset),units, ...
expression,'column_info','columns');
case 'seismic'
if isfield(dataset,'header_info')
[dataset,ier]=convert4header_no3(dataset,units,expression);
end
case 'pseudo-wells'
[dataset,ier]=convert4panels_no4(dataset,units,expression);
if isfield(dataset,'header_info')
[dataset,ier1]=convert4header_no3(dataset,units,expression);
ier=max(ier,ier1);
end
otherwise
error(['Unsupported type of dataset: "',dataset.type,'".'])
end
% Convert units of parameters listed in field "parameter_info" of a dataset
dataset=convert4parameters_no5(dataset,units,expression);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [dataset,ier]=convert4log_and_table_no2(dataset,units,expression,info_field,data_field)
% Check dataset fields
[index,ier]=get_indices_no6(dataset,units,info_field);
if ~ier
old=dataset.(data_field)(:,index); %#ok Matrix "old" is used in "eval"
eval([expression,';']);
dataset.(data_field)(:,index)=new; % Matrix "new" is created in "eval"
alert([' Log curve(s) "',cell2str(dataset.(info_field)(index,1),', '), ...
'" changed to units "',units{2},'".'],'ds_unit_conversion')
dataset.(info_field)(index,2)=units(2);
end
% Handle change in the units for depth
if ~isempty(index) && index(1) == 1 && istype(dataset,'well_log')
dataset.first=dataset.curves(1,1);
dataset.last=dataset.curves(end,1);
old=dataset.step; %#ok Matrix "old" is used in "eval"
eval([expression,';']); % Matrix "new" is created in "eval"
dataset.step=new;
dataset.units=units{2};
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [dataset,ier]=convert4header_no3(dataset,units,expression)
% Check dataset fields
[index,ier]=get_indices_no6(dataset,units,'header_info');
if ~ier
old=dataset.headers(index,:); %#ok Matrix "old is used in "eval"
eval([expression,';']);
dataset.headers(index,:)=new; % Matrix "new" is created in "eval"
alert([' Header(s) "',cell2str(dataset.header_info(index,1),', '), ...
'" changed to units "',units{2},'".'],'ds_unit_conversion')
dataset.header_info(index,2)=units(2);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [dataset,ier]=convert4panels_no4(dataset,units,expression)
% Check dataset fields
[index,ier]=get_indices_no6(dataset,units,'panel_info');
if ~ier
for ii=1:length(index)
panel=dataset.panel_info{index(ii),1};
old=dataset.(panel); %#ok Matrix "old" is used in "eval"
eval([expression,';']); % Matrix "new" is created in "eval"
dataset.(panel)=new;
alert([' Panel "',panel,'" changed to units "',units{2},'".'],'ds_unit_conversion')
dataset.panel_info(index(ii),2)=units(2);
end
end
% Handle change in the units for depth
if strcmp(dataset.units,units{1})
old=[dataset.first,dataset.last,dataset.step]; %#ok Matrix "old" is used in "eval"
eval([expression,';']); % Matrix "new" is created in "eval"
dataset.first=new(1);
dataset.last=new(2);
dataset.step=new(3);
dataset.units=units{2};
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function dataset=convert4parameters_no5(dataset,units,expression)
% Check parameters for units that need to be converted
if isfield(dataset,'parameter_info')
params=dataset.parameter_info(:,1);
for ii=1:length(params)
temp=param_info(dataset,params{ii});
if strcmp(temp{2},units{1})
old=dataset.(params{ii}); %#ok "old is used in "eval"
eval([expression,';']);
% Matrix "new" is created in "eval"
dataset=ds_add_parameter(dataset,new,{params{ii},units{2},temp{3}});
alert([' Parameter "',params{ii},'" changed.'],'ds_unit_conversion')
end
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Check dataset fields
function [index,ier]=get_indices_no6(dataset,units,info_field)
global S4M
ier=false;
index=find(ismember(dataset.(info_field)(:,2),units{1}));
if isempty(index)
if S4M.alert
disp([' Alert from "ds_unit_conversion": no curve/column/header/panel with units "',units{1},'" found.'])
end
ier=true;
elseif length(units) > 2 % Are there specific mnemonics for which to convert units
idx=find(ismember(lower(dataset.(info_field)(index,1)),lower(units(3:end))));
if isempty(idx)
if S4M.alert
disp([' Alert from "ds_unit_conversion": no specified curve/column/header/panel with units "',units{1},'" found.'])
disp([' curves with these units: ', ...
cell2str(dataset.(info_field)(index,1),', ')])
end
ier=true;
else
index=index(idx);
end
end
|
github
|
Abakumov/MLIB-master
|
s_select.m
|
.m
|
MLIB-master/OTHER/SeisLab_10.0301/S4M/Geophysics_3.0/s_select.m
| 10,370 |
utf_8
|
2b25c7e8494ba55b45d88bd6bdf29833
|
function seisout=s_select(seismic,varargin)
% Function extracts subset of seismic input traces. An option also allows changing the time
% range of the output data. If seisout.first < seismic.first and/or seisout.last > seismic.last
% then the trace samples undefined by the input data are set to the null value.
% See also: "s_trace_numbers"
%
% Written by: E. Rietsch: April 15, 2000
% Last updated: April 17, 2008: Input can be vectors of seismic datasets
%
% seisout=s_select(seismic,varargin)
% INPUT
% seismic seismic structure
% varargin one or more cell arrays; the first element of each cell array is a
% keyword string, the following arguments contains a parameter(s).
% Accepted keywords are:
% times For a two-element cell array the second element is a vector
% of time values.For a three-element cell array the second and
% third element contain the time of the first sample and the
% last sample respectively.
% Hence, {'times',first,last} and {'times',[first,'last]}
% generally do different things; the former selects all the
% samples between time "first" and time "last"; the latter
% selects the two samples associated with times "first" and
% time "last"
% Default: {'times',[]} the time range of the datset is retained
% which is equivalent to {'times',seismic.first,seismic.last}
% traces The second element can be a vector 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.
% A "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
% 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))
% Headers are selected as found and are not sorted.
% null Null value to assign to seismic data values for times < seismic.first
% and/or times > seismic.last.
% Default: "null=0" unless seismic has null values; then "null=NaN".
%
% Examples:
% s_select(seismic,{'traces',1:10}) % Select traces 1 to 10
% s_select(seismic,{'traces','trace_no',1:10}) % Same as above
% s_select(seismic,{'traces','trace_no',1,10}) % Same as above
% s_select(seismic,{'times',0,1000},{'traces','cdp',100:10:200})
%
% % Select traces with CDP numbers 100 to 200 with increment 10
% s_select(seismic,{'times',seismic.first:2*seismic.step:seismic.last})
% % Select traces with CDP's 100 and above
% s_select(seismic,{'traces','cdp',100,inf})
% % This is equivalent to the previous function call
% s_select(seismic,{'traces','cdp >= 100'})
% % The following is an even more complex function call
% s_select(seismic,{'traces','iline_no > 1000 & iline_no < 1100 & xline_no == 1000'})
%
% OUTPUT
% seisout seismic output structure
%
% EXAMPLES
% seismic=s_data;
% seismic1=s_select(seismic,{'traces','CDP > 105'});
% s_header(seismic1)
% seismic2=s_select(seismic,{'traces','mod(cdp,2) == 0 & cdp <= 108'});
% s_header(seismic2)
% UPDATE HISTORY
% April 16, 2007: Output has precision of input
global S4M
if ~istype(seismic(1),'seismic')
error('The first input argument, "seismic", must be a seismic data set.')
end
%% Set defaults for input parameters
if isnull(seismic)
param.null=NaN;
else
param.null=0;
end
param.times=[];
param.traces=[];
% Replace defaults by the actual input arguments
param=assign_input(param,varargin,'s_select');
%% Check if input is a datset vector
lseismic=length(seismic);
if lseismic > 1
for ii=lseismic:-1:1
seisout(ii)=s_select(seismic(ii),{'null',param.null}, ...
{'times',param.times},{'traces',param.traces}); %#ok Loop starts with largest index
end
return
end
%% Input is not a dataset vector
seisout=seismic;
precision=class(seismic.traces);
[nsamp,ntr]=size(seismic.traces);
if isempty(param.times)
param.times={seismic.first,seismic.last};
end
% Determine index for times
if iscell(param.times)
ta=param.times{1};
te=param.times{2};
if te < ta
error(['First time (',num2str(ta),' greater than last time (',num2str(te),')'])
end
nta=round((ta-seismic.first)/seismic.step);
ta=nta*seismic.step+seismic.first;
nte=round((te-seismic.first)/seismic.step);
te=nte*seismic.step+seismic.first;
t_index=nta+1:nte+1;
seisout.step=seismic.step;
else
t_index=round((param.times-seismic.first)/seismic.step)+1;
ta=(min(t_index)-1)*seismic.step+seismic.first;
te=(max(t_index)-1)*seismic.step+seismic.first;
if length(t_index) > 1
dt=diff(t_index);
if max(dt) ~= min(dt)
error('Nonuniform time samples selected')
else
seisout.step=dt(1)*seismic.step;
end
else
seisout.step=seismic.step;
end
end
seisout.first=ta;
seisout.last=te;
% Find index for traces
if isempty(param.traces)
h_index=1:ntr;
else
if ~iscell(param.traces)
param.traces={param.traces};
elseif iscell(param.traces{1})
param.traces=param.traces{1};
end
if ~ischar(param.traces{1}) % Traces given explicitely
if length(param.traces) > 1
h_index=max([1,param.traces{1}]):min([size(seismic.traces,2),param.traces{2}]);
else
h_index=param.traces{1};
end
if max(h_index) > ntr
error([' Only ',num2str(ntr),' trace(s) available, but largest trace number selected: ',num2str(max(h_index))])
end
elseif length(param.traces) > 1 % Traces defined via header
header=lower(param.traces{1});
if isfield(seismic,'header_info')
idx=ismember_ordered(lower(seismic.header_info(:,1)),header);
else
idx=[];
end
if isempty(idx)
if strcmp(header,'trace_no')
header_vals=1:ntr;
else
error(['Header "',header,'" is not present in the seismic input dataset.'])
end
else
header_vals=seismic.headers(idx,:);
end
if length(param.traces) == 2 % Range of header values specified
hidx=param.traces{2};
h_index=ismember_ordered(header_vals,hidx);
if isempty(h_index)
error(['Header "',header,'" has no values matching the ones requested.'])
end
else % First and last header value specified
ha=param.traces{2};
he=param.traces{3};
h_index=find(header_vals >= ha & header_vals <= he);
if isempty(h_index)
error(['Header "',header,'" has no values within range specified (',num2str([ha,he]),')'])
end
end
else % Traces defined via logical a expression
h_index=find_trace_index(seismic,param.traces{1});
end
end
% Copy seismic data
if ta < seismic.first || te > seismic.last
if param.null == 0
seisout.traces=zeros(length(t_index),length(h_index),precision);
else
seisout.null=param.null;
seisout.traces=param.null*ones(length(t_index),length(h_index),precision);
end
idxi=find(ismember(1:nsamp,t_index));
bool=ismember(t_index,1:nsamp);
if isempty(idxi)
error([' Time range specified (',num2str(ta),' - ',num2str(te), ...
') does not include time range of input data (', ...
num2str(seismic.first),' - ',num2str(seismic.last),')'])
end
seisout.traces(bool,:,:)=seismic.traces(idxi,h_index,:);
else
seisout.traces=seismic.traces(t_index,h_index,:);
end
% Copy headers
if isfield(seismic,'headers')
seisout.headers=seismic.headers(:,h_index);
end
% Check for existence of null values
bool=any(isnan(seisout.traces(:)));
if bool
seisout.null=NaN;
else
seisout.null=[];
end
% Append history field
if S4M.history && isfield(seismic,'history')
htext=['Times: ',num2str(seisout.first),' - ',num2str(seisout.last),' ',seisout.units,', ', ...
num2str(length(h_index)),' traces'];
seisout=s_history(seisout,'append',htext);
end
if isempty(seisout.traces)
alert(' No traces selected. Empty trace matrix output.')
else
if strcmp(precision,'single')
seisout.null=single(seisout.null);
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function index=find_trace_index(seismic,expression)
% Function finds index of traces whose header values match a logical expression
% INPUT
% seismic seismic data set
% expression logical expression involving header values
% OUTPUT
% index index of trace numbers (traces "seismic.traces(:,h_index)" are selected)
global S4M
words=symvar(expression); % Get all the variable in the expression
if ~S4M.case_sensitive
words=lower(words);
headers=lower(seismic.header_info(:,1));
else
headers=seismic.header_info(:,1);
end
ik=0;
for ii=1:length(words)
temp=find(ismember(headers,words(ii))); %#ok Variable "temp" is used in "eval"
if isempty(temp)
ik=ik+1;
if strcmp(words(ik),'trace_no') % Trace_no is used in expression "expression"
trace_no=1:size(seismic.headers,2); %#ok Required further below in "eval"
end
else
ik=ik+1;
eval([words{ik},'=seismic.headers(temp,:);']);
end
end
if ik == 0
disp([' No header mnemonics in expression "',expression,'".'])
disp(' Available header mnemonics (besides "trace_no") are:')
disp(cell2str(seismic.header_info(:,1),', '));
error(' Abnormal termination')
end
try
index=eval(['find(',lower(expression),')']);
catch %#ok
disp([' The argument of keyword "traces" (',expression,')'])
disp(' is probably not a valid logical expression or a header mnemonic has been misspelled.')
error(' Abnormal termination')
end
|
github
|
Abakumov/MLIB-master
|
l_fill_gaps.m
|
.m
|
MLIB-master/OTHER/SeisLab_10.0301/S4M/Geophysics_3.0/l_fill_gaps.m
| 2,518 |
utf_8
|
fdb2c3c42e285b3ba382f597bbf04495
|
function wlog=l_fill_gaps(wlog,mnemonics)
% Function interpolates across gaps in the log curves (null values) of all
% curves specified by an optional list of mnemonics. The function assumes
% that null values are represented by NaNs.
%
% Date April 29, 2000; written by E. Rietsch
% Last update: June 8, 2004: use "wlog" instead of "log" and "log_out"
%
% wlog=l_fill_gaps(wlog,mnemonics)
% INPUT
% wlog log structure
% mnemonics mnemonic or cell array of mnemonics to interpolate
% if "mnemonics" is not given or empty all curves are
% interpolated
% OUTPUT
% wlog log with interpolated curves; curves not in the list of mnemonics are
% copied unchanged
if ~istype(wlog,'well_log')
error('First input argument must be a well log')
end
if ~isfield(wlog,'null') % If there are no null values in the log curves ...
return
end
[n,m]=size(wlog.curves);
if nargin < 2 || isempty(mnemonics)
idx=2:m;
else
if ischar(mnemonics)
mnemonics={mnemonics};
elseif ~iscell(mnemonics)
error(' Input parameter mnemonics must be a string or a cell array of strings')
end
nm=length(mnemonics);
idx=find(ismember(lower(wlog.curve_info(:,1)),lower(mnemonics)));
if length(idx) ~= nm
disp(' Curves_requested:')
disp(mnemonics)
disp(' Curves_found:')
disp(cell2str(wlog.curve_info(:,1),', '))
error('Number of curves found differs from number requested.')
end
end
if ~isnan(wlog.null)
idx=find(wlog.curves == wlog.null);
wlog.curves(idx)=NaN;
wlog.null=NaN;
end
% wlog.curves=wlog.curves;
for ii=idx(:)'
index=find(~isnan(wlog.curves(:,ii)));
if ~isempty(index) && length(index) ~= n
wlog.curves(index(1):index(end),ii)=fill_gaps(wlog.curves(index(1):index(end),1), ...
wlog.curves(index(1):index(end),ii),index-index(1)+1);
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function curve=fill_gaps(depth,curve,index)
% Function fills gaps in log curve.
% INPUT
% depth uniform depth values
% curve corresponding values of the curve
% index index vector of non-NaN values (i.e. curve(index) is not NaN)
% OUTPUT
% curve input curve with the NaNs replaced by interpolated values
idx=find(diff(index) > 1);
if isempty(idx)
return
end
nidx=length(idx);
for ii=1:nidx
ia=index(idx(ii));
ie=index(idx(ii)+1);
curve(ia+1:ie-1)=interp1q(depth([ia,ie]),curve([ia,ie]),depth(ia+1:ie-1));
end
|
github
|
Abakumov/MLIB-master
|
l_rm_nulls.m
|
.m
|
MLIB-master/OTHER/SeisLab_10.0301/S4M/Geophysics_3.0/l_rm_nulls.m
| 3,849 |
utf_8
|
e0e05817bcc9822f431af8872b5b7a58
|
function wlog=l_rm_nulls(wlog,action,mnemonics)
% Function removes leading and trailing rows from log curves if they contain
% null values; with option "anywhere", every row with a NaN in one of the
% listed curves is removed.
% Null values bracketed by non-null values may be retained. The function assumes
% that null values are represented by NaNs. If this is not the case they are
% replaced by NaNs in the output structure.
%
% Written by: E. Rietsch: March 6, 2000
% Last updated: October 2, 2007: Generalize input to handle dataset vectors; bug fixes
%
% wlog=l_rm_nulls(wlog,action,mnemonics)
% INPUT
% wlog log structure or structure vector
% action optional parameter which controls action to be performed; possible values are:
% 'all' leading and trailing rows are removed if the non-depth
% curves listed in "mnemonics" are all NaN (DEFAULT).
% 'any' leading and trailing rows are removed if any of the non-depth
% curves listed in "mnemonics" has a NAN value
% 'anywhere' every row with a NaN in one of the curves listed
% in "mnemonics" is removed (not just the leading/trailing rows)
% Default: action='all'
% mnemonics optional cell array of mnemonics to be considered
% if not given or if empty then all curves are used
% Default: mnemonics=[];
% OUTPUT
% wlog output log structure
%
% EXAMPLE
% wlog=l_data; % Create log structure with null values
% wlog.curves([1:4,10:20],2)=NaN;
% wlog.null=NaN;
%
% wlog1=l_rm_nulls(wlog,'anywhere',{'DTp','RHO'});
% [isnull(wlog),isnull(wlog1)] % Must be [true,false]
%
% wlog2=l_rm_nulls(wlog,'any',{'DTp','RHO'});
% [isnull(wlog),isnull(wlog2)] % Must be [true,true]
if ~istype(wlog,'well_log')
error('First input argument must be a well log.')
end
if nargin == 1
mnemonics=[];
action='all';
elseif nargin == 2
mnemonics=[];
end
for ii=length(wlog):-1:1
wlog(ii)=rm_nulls_no1(wlog(ii),action,mnemonics); %#ok Loop starts with largest element
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function wlog=rm_nulls_no1(wlog,action,mnemonics)
global S4M
if ~isnull(wlog) % If no null values are present in log curves ...
return
end
m=size(wlog.curves,2);
if nargin < 2 || isempty(action)
action='all';
end
if nargin < 3 || isempty(mnemonics)
idx=2:m;
else
if ischar(mnemonics)
mnemonics={mnemonics};
elseif ~iscell(mnemonics)
error(' Input parameter mnemonics must be a string or a cell array of strings')
end
nm=length(mnemonics);
if S4M.case_sensitive
idx=find(ismember(wlog.curve_info(:,1),mnemonics));
else
idx=find(ismember(lower(wlog.curve_info(:,1)),lower(mnemonics)));
end
if length(idx) ~= nm
disp([char(13),' Curves requested:'])
disp(mnemonics)
disp(' Curves in log structure:')
disp(wlog.curve_info(:,1)')
error(' Not all requested curves available in log structure')
end
end
if ~isempty(wlog.null) && ~isnan(wlog.null) % Replace numeric null value (e.g. -999.25) by NaN
wlog.curves(wlog.curves == wlog.null)=NaN;
wlog.null=NaN;
end
switch action
case {'any','anywhere'}
test=sum(wlog.curves(:,idx),2);
case 'all'
test=min(wlog.curves(:,idx),[],2);
otherwise
error(['Action "',action,'" is not defined'])
end
switch action
case {'anywhere'}
wlog.curves=wlog.curves(~isnan(test),:);
otherwise
ia=find(~isnan(test),1);
ie=find(~isnan(test),1,'last');
wlog.curves=wlog.curves(ia:ie,:);
end
wlog.first=wlog.curves(1,1);
wlog.last=wlog.curves(end,1);
wlog.step=depths2step_with_checking(wlog.curves(:,1));
% Check if "wlog.null" needs to be changed
if all(all(~isnan(wlog.curves(:,2:end))))
wlog.null=[];
end
|
github
|
Abakumov/MLIB-master
|
s_header_plot.m
|
.m
|
MLIB-master/OTHER/SeisLab_10.0301/S4M/Geophysics_3.0/s_header_plot.m
| 7,177 |
utf_8
|
19eaab2240f0108d28d01b9cbd45362d
|
function aux=s_header_plot(seismic,headers,varargin)
% Function plots values of seismic headers
%
% Written by: E. Rietsch: July 22, 2000
% Last updated: January 30, 2007: add cursor tracking
%
% aux=s_header_plot(seismic,headers,varargin)
% INPUT
% seismic seismic structure whose headers should be plotted
% headers header mnemonic or cell array with header mnemonics
% if one header mnemonic is given it is plotted as a function of trace number
% if two or more headers are specified, the first one represents the x-axis;
% the other headers are plotted against the first
% if the the headers are to be plotted against the trace number, the first
% element of cell array headers can be the empty string ('') or 'trace_no'
% No defaults.
% Examples: 'cdp', {'trace_no','iline_no','xline_no'}, {'cdp_x','cdp_y'}
% varargin one or more cell arrays; the first element of each cell array is a
% keyword, the other elements are parameters. Presently, keywords are:
% 'colors' Colors to be used for consecutive curves.
% Possible values: any permissible colors and line styles
% Default: {'colors','r','g','b','m','k','c', ...
% 'r--','g--','b--','m--','k--','c--', ...
% 'r:','g:','b:','m:','k:','c:'};
% 'linewidth' Width of the lines. Default: {'linewidth',2}
% 'figure' If set to 'new' a new figure is created. Any other string
% plots to the current axes of an existing figure.
% Default: {'figure','new'}
% 'orient' Possible values are 'portrait' and 'landscape'.
% Default: 'landscape'.
% 'scale' 2-element cell array which specifies if curves should
% be scaled individually. Possible values are 'yes' or 'no'.
% Default: {'scale','yes'}
% 'title' Plot title. Default: 'Headers of seismic data set "seismic"'
% where "seismic" is the name of the seismic data set (first input argument)
% OUTPUT
% aux structure with possibly relevant information
% figure_handle figure handle
% curve_handles vector with the curve handles, so that curve attributes can be changed
if ~istype(seismic,'seismic')
error(' First input argument must be a seismic dataset.')
end
% Set default values
param.colors={'r','g','b','m','k','c','r--','g--','b--','m--','k--','c--', ...
'r:','g:','b:','m:','k:','c:'};
param.figure='new';
param.linewidth=2;
param.lloc=[];
param.orient='landscape';
param.scale='yes';
param.title='';
% Decode and assign input arguments
param=assign_input(param,varargin);
if ~iscell(param.colors)
param.colors={param.colors};
end
% Check if new figure is requested
if strcmpi(param.figure,'new')
if strcmpi(param.orient,'portrait')
figure_handle=pfigure;
else
figure_handle=lfigure;
end
if isempty(param.title)
mytitle(['Headers of seismic data set "', ...
strrep(seismic.name,'_','\_'),'"'])
else
mytitle(param.title)
end
end
hold on
if iscell(headers) && length(headers) > 1
if isempty(headers{1}) || strcmpi(headers{1},'trace_no')
x=1:size(seismic.headers,2);
idx=header_index(seismic,headers(2:end));
xlabel('Trace number')
xinfo={'trace_no,','n/a','Trace number'};
else
idx=header_index(seismic,headers);
x=seismic.headers(idx(1),:);
xlabel(header_label(seismic.header_info(idx(1),:)))
xinfo=seismic.header_info(idx(1),:);
idx=idx(2:end);
end
curve_handles=zeros(length(headers)-1,1);
ltext=cell(length(headers)-1,1);
for ii=2:length(headers)
if length(headers) > 2 && strcmpi(param.scale,'yes')
curve_handles(ii-1)=plot(x,seismic.headers(idx(ii-1),:)/max(abs(seismic.headers(idx(ii-1),:))), ...
param.colors{ii-1},'LineWidth',param.linewidth);
else
curve_handles(ii-1)=plot(x,seismic.headers(idx(ii-1),:), ...
param.colors{ii-1},'LineWidth',param.linewidth);
end
ltext(ii-1)={strrep(headers{ii},'_','\_')};
end
if length(headers) > 2
if isempty(param.lloc) % Set location of legend
loc=1;
else
loc=param.lloc;
end
legend(char(ltext),loc);
if strcmpi(param.scale,'yes')
ylabel('Values scaled to a maximum of 1')
end
else
ylabel(header_label(seismic.header_info(idx,:)))
end
initiate_2d_tracking(xinfo,{'header_value','','Header value'})
else
if iscell(headers), headers=headers{1}; end
if iscell(param.colors), param.colors=param.colors{1}; end
idx=header_index(seismic,headers);
curve_handles=plot(seismic.headers(idx,:),param.colors(1),'LineWidth',param.linewidth);
xlabel('Trace number')
yinfo=seismic.header_info(idx,:);
ylabel(header_label(yinfo))
initiate_2d_tracking({'trace_no','n/a','Trace number'},yinfo)
end
grid on
zoom on
if nargout == 1
aux.figure_handle=figure_handle;
aux.curve_handles=curve_handles;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function text=header_label(header_info)
% Function composes a label for plots from the header information in header_info
% INPUT
% header_info Cell array; second element represents header units, third element
% header description
% OUTPUT
% text text for headef label in plots
text=strrep(header_info{3},'_','\_');
if ~isempty(header_info{2}) && ~strcmpi(header_info{2},'n/a')
text=[text,' (',header_info{2},')'];
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [index,ier]=header_index(seismic,varargin)
% Function outputs index (indices) of header(s) "headers" in seismic structure "seismic".
% Aborts with an error message if one or more of the headers do not exist.
% [index,ier]=header_index(seismic,varargin)
% INPUT
% seismic seismic structure whose headers are requested
% varargin one or more header mnemonics
% OUTPUT
% index index into fields header_info and headers (the headers are seismic.headers(index,:)
% and the header information is seismic.header_info(index,:))
% ier error code; if a second output argument is specified the function will not abort
% if one or more header nmemonics are not found. It will issue a message and
% return with "ier" set to 1. If no error exists, "ier" is set to 0.
ier=0;
if iscell(varargin{:})
varargin=varargin{:};
end
index=zeros(length(varargin),1);
for ii=1:length(varargin)
[idx,ier1]=header_index1(seismic,varargin{ii});
% idx=find(ismember(seismic.header_info(:,1),lower(char(varargin{ii}))));
if ier1
ier=1;
disp([' Header "',varargin{ii},'" does not exist.'])
else
index(ii)=idx;
end
end
if ier == 1
% temp=[char(seismic.header_info{:,1})';blanks(size(seismic.header_info,1))]';
disp(' The following header mnemonics exist: ')
disp(seismic.header_info(:,1)');
if nargout < 2
error(' Abnormal Termination')
end
end
|
github
|
Abakumov/MLIB-master
|
s_create_wavelet.m
|
.m
|
MLIB-master/OTHER/SeisLab_10.0301/S4M/Geophysics_3.0/s_create_wavelet.m
| 11,528 |
utf_8
|
b107a72e1ba7e62f5c7bb999abb45eba
|
function wav=s_create_wavelet(varargin)
% Function computes wavelet and stores it in a seismic data structure; The
% wavelet is scaled in such a way that its maximum amplitude (maximum of the
% instantaneous amplitude in case of a non-zero-phase wavelet) is equal to 1.
%
% See also: s_create_spike
%
% Written by: E. Rietsch: April 15, 2000
% Last updated: May 19, 2008: bug fix
%
% wav=s_create_wavelet(varargin)
% INPUT
% varargin one or more cell arrays; the first element of each cell array is a
% keyword, the other elements are parameters. Presently, keywords are:
% 'type' Type of wavelet. Possible options are:
% Ormsby wavelets with:
% 'zero-phase' zero-phase wavelet with trapezoidal
% spectrum defined via keyword 'frequencies'
% 'min-phase' minimum-phase wavelet with trapezoidal
% spectrum defined via keyword 'frequencies'
% 'max-phase' maximum-phase wavelet with trapezoidal
% spectrum defined via keyword 'frequencies'
% or
% 'ricker' Ricker wavelet
% Default: {'type','zero-phase'}
% 'frequencies' For Ormsby wavelets:
% the four corner frequencies, f1,f2,f3,f4, of a trapezoidal
% amplitude spectrum. The corner frequencies must satisfy
% the condition 0 <= f1 <= f2 <= f3 <= f4.
% Default: {'frequencies',10,20,40,60} or, in equivalent notation,
% {'frequencies',[10,20,40,60]}
% For Ricker wavelet: the location of the spectral peak
% Default: {'frequencies',30}
% 'wlength' the length of the filter in ms (if wavelet "type" is
% 'zero-phase' or 'ricker' then 'length' should be an even
% multiple of the sample interval);
% Default: {'length',120};
% If this is not the case it is increased by the sample interval.
% 'step' sample interval in ms. Default: {'step',4}
% 'option' In the trade-off between zero-phase property and match to
% the design amplitude spectrum this parameter determines
% what to favor.
% Possible values are: 'amp', 'phase' (requires long wavelet)
% Default: {'option'.'amp'}
% Ignored for Ricker wavelet
% 'window' Apply a window to the wavelet to reduce end effects (only
% for Ormsby wavelets; a half window is used for minimum-phase
% and maximum-phase wavelets). Makes the wavelet spectrum smoother.
% Possible windows are (case-insensitive):
% 'Hamming', 'Hanning', 'Nuttall', 'Papoulis', 'Harris',
% 'Rect', 'Triang', 'Bartlett', 'BartHann', 'Blackman'
% 'Gauss', 'Parzen', 'Kaiser', 'Dolph', 'Hanna'.
% 'Nutbess', 'spline', 'none'
% Default: {'window','Parzen'}
% 'dc_removal' Remove DC component (only for zero-phase wavelet)
% Possible values are: 'yes' and 'no'
% Default: {'dc_removal','yes'}
% OUTPUT
% wav wavelet in form of a seismic structure; the wavelet is scaled in
% such a way that the maximum of its Hilbert amplitude is 1.
% For wavelets of type 'Ricker' and type 'zero-phase' this means
% that the maximum amplitude of the wavelet is 1 as well.
%
% EXAMPLES
% wav=s_create_wavelet
% wav=s_create_wavelet({'type','min-phase'},{'frequencies',10,10,40,80},{'step',2})
% wavelet=s_create_wavelet({'type','ricker'},{'frequencies',25'})
% UPDATE HISTORY
% September 20, 2007: Prevent window name from being added to
% dataset name
global S4M
run_presets_if_needed
history=S4M.history;
S4M.history=0;
% Set defaults
param.dc_removal='yes'; % Remove DC component (only for zero=phase wavelets)
param.frequencies=[];
param.length=[]; % Deprecated parameter
param.option='amp';
param.step=4;
param.type='zero-phase';
param.units='ms';
param.window='Parzen';
param.wlength=120;
% Decode and assign input arguments
param=assign_input(param,varargin,'s_create_wavelet');
if ~isempty(param.length)
param.wlength=param.length;
disp(' Parameter "length" has been deprecated. In the future please use "wlength" instead.')
end
wav.type='seismic';
wav.tag='wavelet';
wav.name='';
% Compute Ricker wavelet
if strcmpi(param.type,'ricker')
if isempty(param.frequencies)
param.frequencies=30;
end
wav.name=['Ricker wavelet (',num2str(param.frequencies),' Hz)'];
wl2=round(0.5*param.wlength/param.step)*param.step;
wav.first=-wl2;
wav.last=wl2;
wav.step=param.step;
wav.units=param.units;
% Compute Ricker wavelet
beta=((-wl2:param.step:wl2)'*(param.frequencies*pi*0.001)).^2;
wav.traces=(1.-beta.*2).*exp(-beta);
wav.traces=wav.traces./max(wav.traces);
wave.traces.null=[];
% Create history field
if S4M.history
wav=s_history(wav,'add',['Ricker wavelet with peak frequency at ',num2str(param.frequencies)]);
end
% Convert to requested precision
if strcmpi(S4M.precision,'single')
wav=single(wav);
end
return
end
% Compute Ormsby wavelets
if isempty(param.frequencies)
param.frequencies=[10,20,40,60];
end
if iscell(param.frequencies) && length(param.frequencies) == 4
f1=param.frequencies{1};
f2=param.frequencies{2};
f3=param.frequencies{3};
f4=param.frequencies{4};
else
if iscell(param.frequencies)
param.frequencies=cell2mat(param.frequencies);
end
f1=param.frequencies(1);
f2=param.frequencies(2);
f3=param.frequencies(3);
f4=param.frequencies(4);
end
if any(diff([f1;f2;f3;f4]) < 0)
htext=num2str([f1,f2,f3,f4]);
error([' Corner frequencies for wavelet spectrum are not monotonic: ',htext]);
end
nsamp=floor(param.wlength/param.step)+1;
wav.name=['Ormsby (' param.type,', ',num2str(f1),'-',num2str(f2),'-', ...
num2str(f3),'-',num2str(f4),' Hz)'];
switch param.type
case 'zero-phase'
htext=num2str([f1,f2,f3,f4]);
wav.first=-fix(nsamp/2)*param.step;
wav.last=-wav.first;
if strcmpi(param.option,'amp')
wav.traces=zero_phase_wavelet(nsamp,param.step,f1,f2,f3,f4);
elseif strcmpi(param.option,'phase')
wav.traces=zss_wavelet(nsamp,param.step,f1,f2,f3,f4);
else
error([' Unknown value (',param.option,') for parameter "option"'])
end
htext=['Zero-phase wavelet: corner frequencies ',htext];
if ~strcmp(param.window,'none') || ~strcmp(param.window,'no')
wav=s_window(wav,param.window,{'add_window2name',false});
end
if isyes(param.dc_removal)
wav.traces=lf_dc_removal(wav.traces,2);
% times=linspace(wav.first,wav.last,length(wav.traces))';
% aa=cos(0.5*pi*times/times(end)).^2;
% wav.traces=wav.traces-(sum(wav.traces)/sum(aa))*aa;
end
wav.traces=wav.traces/max(wav.traces);
case {'min-phase','max-phase'}
htext=num2str([f1,f2,f3,f4]);
wav.first=0;
wav.last=param.wlength;
wav.traces=minimum_phase_wavelet(nsamp,param.step,f1,f2,f3,f4);
if strcmpi(param.type,'min-phase')
htext=['Minimum-phase wavelet: corner frequencies ',htext];
if ~strcmp(param.window,'none') || ~strcmp(param.window,'no')
wav=s_window(wav,param.window,{'option',-1},{'add_window2name',false});
end
else
htext=['Maximum-phase wavelet: corner frequencies ',htext];
wav.first=-param.wlength;
wav.last=0;
wav.traces=flipud(wav.traces);
if ~strcmp(param.window,'none') || ~strcmp(param.window,'no')
wav=s_window(wav,param.window,{'option',1},{'add_window2name',false});
end
end
wav.traces=wav.traces/max(abs(myhilbert(wav.traces)));
otherwise
disp([char(13),' Unknown wavelet type: ',param.type])
disp(' Possible values are: zero-phase, min-phase, max-phase')
error(' Abnormal termination')
end
wav.step=param.step;
wav.units=param.units;
wav.null=[];
% Create history field
S4M.history=history;
wav=s_history(wav,'add',htext);
% Convert to requeste precision
if strcmpi(S4M.precision,'single')
wav=single(wav);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function wav=zero_phase_wavelet(nsamp,dt,f1,f2,f3,f4)
% Function computes zero-phase wavelet for a trapezoidal spectrum.
% For use within a subroutine; therefore no argument checks
%
% INPUT
% nsamp number of samples (if even a sample will be appended to male it odd)
% dt sample interval
% f1, f2, f3, f4 corner frequencies of trapezoid
% OUTPUT
% wav zero-phase wavelet
if ~mod(nsamp,2)
nsamp=nsamp+1;
end
temp=zeros(nsamp,1);
temp(fix(nsamp/2)+1)=1;
wav=ormsby(temp,dt,f1,f2,f3,f4);
wav([1,end])=wav([1,end])*0.5;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function fa=zss_wavelet(nsamp,dt,f1,f2,f3,f4)
% Function computes zero-phase wavelet with trapezoidal corner
% frequencies f1, f2, f3, f4 as the correlation of a zero-phase wavelet
% of half the length and and with the square root of the design spectrum.
% The function is for internal use and performs no error checking
%
% INPUT
% nsamp number of samples
% dt sample interval in ms
% f1 f2 f3 f4 corner frequencies (0 <= f1 <= f2 <= f3 <= f4 <= fnyquist)
% OUTPUT
% fa filtered input array
% fa=ormsby(nsamp,dt,f1,f2,f3,f4)
n=fix(nsamp/2)+1;
nh=fix((n+1)/2);
fnyquist=500/dt;
% df=2*fnyquist/n;
% f=[0:df:fnyquist];
f=(0:2:n)*fnyquist/n;
% Compute trapezoidal window to apply to spectrum
trapez=zeros(n,1);
idx=find(f >= f1 & f <= f4);
f=f(idx);
eps1000=1000*eps;
b1=(f-f1+eps1000)/(f2-f1+eps1000);
b2=ones(1,length(b1));
b3=(f4-f+eps1000)/(f4-f3+eps1000);
trapez(idx)=min([b1;b2;b3]);
trapez(n:-1:n-nh+2)=trapez(2:nh);
% Perform inverse FFT of the square root of the trapezoidal spectrum
% and form autocorrelation of the resulting wavelet
gh=sqrt(trapez);
fa=real(ifft(gh));
fa=[fa(nh+1:end);fa(1:nh)];
fa=correlate(fa,fa);
%fa=corr(fa,fa);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function wav=minimum_phase_wavelet(nsamp,dt,f1,f2,f3,f4)
% Function computes minimum-phase wavelet for a trapezoidal spectrum.
% For use within a subroutine; therefore no argument checks
% INPUT
% nsamp number of samples (if even a sample will be appended to make it odd)
% dt sample interval
% f1, f2, f3, f4 corner frequencies of trapezoid
% OUTPUT
% wav minimum-phase wavelet
wav0=zero_phase_wavelet(nsamp,dt,f1,f2,f3,f4);
nfft=pow2(nextpow2(nsamp)+1);
fwav=fft(wav0,nfft);
fwav=abs(fwav);
% amp=convolve([0.25;0.5;0.25],[fwav(end);fwav;fwav(1)]);
amp=convolve([0.25;0.5;0.25],[fwav(1);fwav;0]);
wav=minimum_phase(amp(3:end-2),nsamp);
[dummy,index]=max(abs(wav));
if wav(index) > 0
wav=wav*norm(wav0)/norm(wav);
else
wav=-wav*norm(wav0)/norm(wav);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function wav=minimum_phase(amp,nsamp)
% Function computes minimum-phase wavelet with given amplitude spectrum
% INPUT
% amp amplitude spectrum
% nsamp number of samples of desired wavelet
% dt sample interval of wavelet
% OUTPUT
% wav minimum-phase wavelet with amplitude spectrum "amp"
temp=fft(log(amp));
namp=length(amp);
namph=fix(namp/2);
temp=real(temp(2:namph+1)).*(1:namph)'/namph;
wav=ones(nsamp,1);
wav(2)=temp(1);
for ii=2:nsamp-1
wav(ii+1)=sum(wav(ii:-1:1).*temp(1:ii))/ii;
end
|
github
|
Abakumov/MLIB-master
|
s_seismic2wavelet.m
|
.m
|
MLIB-master/OTHER/SeisLab_10.0301/S4M/Geophysics_3.0/s_seismic2wavelet.m
| 8,709 |
utf_8
|
ddc4f9f4a651e2e8c10f2d884d947769
|
function wavelet=s_seismic2wavelet(seismic,varargin)
% Function computes wavelet with about the spectrum expected on the basis of the
% seismic data. The wavelet can be minimum-phase, zero-phase, or
% maximum-phase. The amplitude is based on the windowed autocorrelation of the
% seismic data.
%
% Written by: E. Rietsch: June 15, 2001
% Last updated: September 2, 2007: general update
%
% wavelet=s_seismic2wavelet(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:
% 'nodc' Determines if DC component of wavelet should be removed (no DC).
% Possible values are: true (yes) and false (no)
% Default: {'nodc',true}
% 'wlength' wavelet length. For symmetric wavelets this should be an even
% multiple of the sample interval. An optional second parameter
% can be used to indicate if the wavelet length is to be exact
% ('exact') or an approximation ('approx'). In the latter case
% the actual length of the wavelet is chosen so that it ends
% just prior to a zero crossing
% Default: {'length',80,'approx'}
% 'color' Color of reflectivity. Possible values are 'white' and 'blue'.
% If 'blue', the amplitude spectrum of the reflectivity is assumed to be
% proportional to the square root of the frequency.
% Default: {'color','blue'}
% 'type' type of wavelet. Possible options are:
% 'zero-phase' zero-phase wavelet
% 'min-phase' minimum-phase wavelet
% 'max-phase' maximum-phase wavelet
% Default: {'type','zero-phase'}
% 'window' type of window to use. Possible values are (not case-sensitive):
% 'Hamming', 'Hanning', 'Nuttall', 'Papoulis', 'Harris',
% 'Rect', 'Triang', 'Bartlett', 'BartHann', 'Blackman'
% 'Gauss', 'Parzen', 'Kaiser', 'Dolph', 'Hanna',
% 'Nutbess', 'spline', 'none'
% (the empty string means no window, 'Rect' and 'none' are
% equivalent)
% Default: {'window','Hanning'}
%
% OUTPUT
% wavelet seismic structure with desired wavelet; the wavelet is scaled
% in such a way that the maximum of the absolute value of the
% wavelet samples is equal to 1.
%
% EXAMPLE
% % Compute minimum-phase wavelet from seismic data
% seismic=s_data;
% minwav=s_seismic2wavelet(seismic,{'color','blue'},{'type','min-phase'},{'wlength',80});
% s_wplot(minwav)
% s_spectrum(minwav,{'plot','both'},{'timezero','actual'})
global S4M
history=S4M.history;
S4M.history=false;
% Assign default values of input arguments
param.color='blue';
param.dc=[];
param.length=[];
param.nodc=true;
param.type='zero-phase';
param.window='Hanning';
param.wlength=80;
% Decode and assign input arguments
param=assign_input(param,varargin,'s_seismic2wavelet');
% Handle legacy parameter
if ~isempty(param.length)
alert('Use of keyword "length" is obsolete. Use "wlength" instead.')
param.wlength=param.length;
end
if ~isempty(param.dc)
alert('Use of keyword "dc" is obsolete. Please use "nodc" instead (see help s_seismic2wavelet.')
param.nodc=param.dc;
end
% Check if "wlength" has a second parameter.
if iscell(param.wlength)
len=param.wlength{1};
param.lopt=param.wlength{2};
else
len=param.wlength;
param.lopt='approx';
end
param.nlag=round(0.5*len/seismic.step);
param.lag=param.nlag*seismic.step;
if strcmpi(param.window,'none')
param.window='rect';
end
%ntr=size(seismic.traces,2);
% Remove leading and trailing null values in the trace data and replace others by zeros
if isnull(seismic)
seismic=s_rm_trace_nulls(seismic);
disp(['Dataset "',seismic.name,'" has null values; they have been replaced by zeros.'])
end
switch param.type
case 'zero-phase'
wavelet=zero_phase_wavelet_no1(seismic,param);
case {'min-phase','max-phase'}
wavelet=min_max_phase_wavelet_no2(seismic,param);
otherwise
error([' Unknown or un-implemented type: "',param.type,'"'])
end % End of switch block
% Scaling
wavelet.traces=wavelet.traces/max(abs(wavelet.traces));
S4M.history=history;
wavelet.tag='wavelet';
wavelet.window_type=param.window;
if strcmpi(param.color,'blue')
wavelet.info={'Wavelet estimation method: ', ...
'Wavelet estimate from seismic (blue reflectivity)'};
else
wavelet.info={'Wavelet estimation method: ', ...
'Wavelet estimate from seismic (white reflectivity)'};
end
if isfield(seismic,'history')
wavelet.history=seismic.history;
wavelet=s_history(wavelet,'append',['Window-type: ',param.window, ...
'; length: ',num2str(len),' ms']);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function wavelet=zero_phase_wavelet_no1(seismic,param)
% Compute zero-phase wavelet from seismic
% Compute the spectrum of the wavelet
aspectrum=compute_spectrum_no3(seismic,param);
% Raw wavelet
filt=fftshift(real(ifft(aspectrum)));
% Determination of wavelet length
nlag=param.nlag;
if strcmp(param.lopt,'approx')
index=find(filt(1:nlag+1).*filt(2:nlag+2) <= 0,1,'last');
if isempty(index)
filt=filt(nlag+1:end-nlag);
else
nlag=index;
filt=filt(nlag+1:end-nlag);
end
else
filt=filt(nlag+1:end-nlag);
end
if isyes(param.nodc) % Remove DC component
filt=filt-0.5*(filt(1)+filt(end));
filt=lf_dc_removal(filt,1);
else
filt([1,end])=0.5*filt([1,end]);
end
htext='Zero phase wavelet';
first=0.5*(1-length(filt))*seismic.step;
wavelet=s_convert(filt,first,seismic.step,htext,seismic.units);
wavelet.name='Zero-phase wavelet from seismic';
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function wavelet=min_max_phase_wavelet_no2(seismic,param)
% Compute minimum-phase or maximum-phase wavelet from seismic
% Compute the spectrum of the wavelet
aspectrum=compute_spectrum_no3(seismic,param,64*param.nlag);
nlag2=round(param.wlength/seismic.step)+1;
filt=minimum_phase(aspectrum,nlag2);
%sort(abs(roots(filt)))'
if strcmp(param.lopt,'approx')
index=find(filt(nlag2-1:end-1).*filt(nlag2:end) <= 0,1);
if ~isempty(index)
nlag2=index+nlag2-2;
filt=filt(1:nlag2);
end
end
if strcmpi(param.type,'min-phase')
htext='Minimum-phase wavelet';
wavelet=s_convert(filt,0,seismic.step,htext,seismic.units);
wavelet.name='Minimum-phase wavelet from seismic';
else
htext='Maximum-phase wavelet';
wavelet=s_convert(flipud(filt),(1-nlag2)*seismic.step,seismic.step,htext, ...
seismic.units);
wavelet.name='Maximum-phase wavelet from seismic';
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function aspectrum=compute_spectrum_no3(seismic,param,nfft)
% Compute the amplitude spectrum of a wavelet from seismic data
lag2=2*param.lag;
% Compute the mean autocorrelation of the seismic
temp=s_correlate(seismic,seismic,{'lags',-lag2,lag2},{'normalize','no'}, ...
{'option','corresponding'});
[nsamp,ntr]=size(temp.traces);
if ntr > 1
traces=mean(temp.traces,2);
end
% Apply taper (if requested)
if ~isempty(param.window) || strcmpi(param.window,'none') || strcmpi(param.window,'rect')
w=mywindow(nsamp,param.window);
traces=w.*traces;
end
% Remove the DC component (if requested)
if isyes(param.nodc)
traces=lf_dc_removal(traces,1);
end
% Compute spectrum of wavelet
if nargin > 2
aspectrum=sqrt(abs(fft(traces,nfft)));
else
aspectrum=sqrt(abs(fft(traces)));
end
% Correct the spectrum for the color of the reflectivity
switch param.color
case 'blue'
nsamp=length(aspectrum)-1;
refl=min((1:nsamp)',(nsamp:-1:1)'); %#ok This is still the better approach
refl=sqrt(refl);
aspectrum(2:end)=aspectrum(2:end)./refl;
aspectrum(1)=0;
case 'bluish' % Mixture of white and blue
nsamp=length(aspectrum)-1;
refl=min((1:nsamp)',(nsamp:-1:1)'); %#ok This is still the better approach
refl=sqrt(refl);
[dummy,index]=max(aspectrum); %#ok First output argument is not required
refl=refl+refl(index);
aspectrum(2:end)=aspectrum(2:end)./refl;
aspectrum(1)=0;
case 'white'
% do nothing
otherwise
error('Unknown color of reflectivity has been specified. Possible values are: "blue" and "white".')
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.