forked from episodes-platform/shared-snippets
70 lines
2.0 KiB
Mathematica
70 lines
2.0 KiB
Mathematica
|
function [] = sac2ascii(sac, asciiFilePath)
|
||
|
%sac2ascii Saves given sac data in ascii file in slist format
|
||
|
|
||
|
% check required fields
|
||
|
checkValue(sac.knetwk, 'knetwk');
|
||
|
checkValue(sac.kstnm, 'kstnm');
|
||
|
checkValue(sac.kcmpnm, 'kcmpnm');
|
||
|
checkValue(sac.delta, 'delta');
|
||
|
checkValue(sac.nzyear, 'nzyear');
|
||
|
checkValue(sac.nzjday, 'nzjday');
|
||
|
checkValue(sac.nzhour, 'nzhour');
|
||
|
checkValue(sac.nzmin, 'nzmin');
|
||
|
checkValue(sac.sec, 'sec');
|
||
|
|
||
|
networkCode = sac.knetwk;
|
||
|
stationCode = sac.kstnm;
|
||
|
locationCode = sac.khole;
|
||
|
if isUndefined(locationCode); locationCode = ''; end
|
||
|
channelCode = sac.kcmpnm;
|
||
|
frequency = int32(1 / sac.delta);
|
||
|
unit = extractUnit(sac);
|
||
|
startTime = extractStartTime(sac);
|
||
|
samples = length(sac.trace);
|
||
|
|
||
|
fileID = fopen(asciiFilePath, 'w');
|
||
|
fprintf(fileID, 'TIMESERIES %s_%s_%s_%s, %d samples, %d sps, %s, SLIST, FLOAT, %s\n',...
|
||
|
networkCode, stationCode, locationCode, channelCode, samples, frequency, startTime, unit);
|
||
|
fprintf(fileID, '%f\n', sac.trace);
|
||
|
fclose(fileID);
|
||
|
|
||
|
end
|
||
|
|
||
|
function [unit] = extractUnit(sac)
|
||
|
switch sac.idep
|
||
|
case 6
|
||
|
unit = 'NM';
|
||
|
case 7
|
||
|
unit = 'NM/S';
|
||
|
case 8
|
||
|
unit = 'NM/S^2';
|
||
|
otherwise
|
||
|
unit = 'COUNTS';
|
||
|
end
|
||
|
end
|
||
|
|
||
|
function [startTime] = extractStartTime(sac)
|
||
|
% converting day of the year to day of the month
|
||
|
yearString = ['01-01-', num2str(sac.nzyear)];
|
||
|
date = datenum(yearString, 'dd-mm-yyyy') + sac.nzjday - 1;
|
||
|
dateString = datestr(date, 'yyyy-mm-dd');
|
||
|
|
||
|
startTime = sprintf('%sT%02d:%02d:%09.6f', dateString, sac.nzhour, sac.nzmin, sac.sec);
|
||
|
end
|
||
|
|
||
|
function [] = checkValue(value, fieldName)
|
||
|
if isUndefined(value)
|
||
|
error('sac does not contain required field - [%s]', fieldName);
|
||
|
end
|
||
|
end
|
||
|
|
||
|
function [undefined] = isUndefined(value)
|
||
|
if isa(value, 'char')
|
||
|
undefined = strcmp(value, '-12345');
|
||
|
elseif isa(value, 'logical')
|
||
|
undefined = value == false;
|
||
|
else
|
||
|
undefined = abs(-12345 - value) < 1e-10;
|
||
|
end
|
||
|
end
|