%% Loma Prieta Earthquake Analysis
% This example shows how to analyze and visualize earthquake data.
%
%% Load Earthquake Data
% The file quake.mat contains 200Hz data from the October 17, 1989 Loma Prieta earthquake in the Santa Cruz Mountains. The data are courtesy of Joel Yellin at the Charles F. Richter Seismological Laboratory, University of California, Santa Cruz.
% Start by loading the data.

load quake 
whos e n v

%
% In the workspace there are three variables, containing time traces from an accelerometer located in the Natural Sciences building at UC Santa Cruz. The accelerometer recorded the main shock amplitude of the earthquake wave. The variables n, e, v refer to the three directional components measured by the instrument, which was aligned parallel to the fault, with its N direction pointing in the direction of Sacramento. The data are uncorrected for the response of the instrument.
% Create a variable, Time, containing the timestamps sampled at 200Hz with the same length as the other vectors. Represent the correct units with the seconds function and multiplication to achieve the Hz (s^{-1}) sampling rate. This results in a duration variable which is useful for representing elapsed time.

Time = (1/200)*seconds(1:length(e))';
whos Time

%
%% Organize Data in Timetable
% Separate variables can be organized in a table or timetable for more convenience. A timetable provides flexibility and functionality for working with time-stamped data. Create a timetable with the time and three acceleration variables and supply more meaningful variable names. Display the first eight rows using the head function.

varNames = {'EastWest', 'NorthSouth', 'Vertical'};
quakeData = timetable(Time, e, n, v, 'VariableNames', varNames);
head(quakeData)

%
% Explore the data by accessing the variables in the timetable with dot subscripting. (For more information on dot subscripting, see Access Data in a Table.) We chose "East-West" amplitude and plot it as function of the duration.

plot(quakeData.Time,quakeData.EastWest)
title('East-West Acceleration')

%
%% Scale Data
% Scale the data by the gravitational acceleration, or multiply each variable in the table by the constant. Since the variables are all of the same type (double), you can access all variables using the dimension name, Variables. Note that quakeData.Variables provides a direct way to modify the numerical values within the timetable.

quakeData.Variables = 0.098*quakeData.Variables;

%
%% Select Subset of Data for Exploration
% We are interested in the time region where the amplitude of the shockwave starts to increase from near zero to maximum levels. Visual inspection of the above plot shows that the time interval from 8 to 15 seconds is of interest. For better visualization we draw black lines at the selected time spots to draw attention to that interval. All subsequent calculations will involve this interval.

t1 = seconds(8)*[1;1];
t2 = seconds(15)*[1;1];
hold on 
plot([t1 t2],ylim,'k','LineWidth',2)
hold off

%
%% Store Data of Interest
% Create another timetable with data in this interval. Use timerange to select the rows of interest.

tr = timerange(seconds(8),seconds(15));
dataOfInterest = quakeData(tr,:);
head(dataOfInterest)

%
% Visualize the three acceleration variables on three separate axes.

figure
subplot(3,1,1)
plot(dataOfInterest.Time,dataOfInterest.EastWest)
ylabel('East-West')
title('Acceleration')
subplot(3,1,2)
plot(dataOfInterest.Time,dataOfInterest.NorthSouth)
ylabel('North-South')
subplot(3,1,3)
plot(dataOfInterest.Time,dataOfInterest.Vertical)
ylabel('Vertical')

%
%% Calculate Summary Statistics
% To display statistical information about the data we use the summary function.

summary(dataOfInterest)

%
% Additional statistical information about the data can be calculated using varfun.This is useful for applying functions to each variable in a table or timetable. The function to apply is passed to varfun as a function handle. Below we apply the mean function to all three variables and output the result in format of a table, since the time is not meaningful after computing the temporal means.

mn = varfun(@mean,dataOfInterest,'OutputFormat','table')

%
%% Calculate Velocity and Position
% To identify the speed of propagation of the shockwave, we integrate the accelerations once. We use cumulative sums along the time variable to get the velocity of the wave front.

edot = (1/200)*cumsum(dataOfInterest.EastWest);
edot = edot - mean(edot);

%
% Below we perform the integration on all three variables to calculate the velocity. It is convenient to create a function and apply it to the variables in the timetable with varfun. In this example, we included the function at the end of this file and named it velFun.

vel = varfun(@velFun,dataOfInterest);
head(vel)

%
% Apply the same function velFun to the velocities to determine the position.

pos = varfun(@velFun,vel);
head(pos)

%
% Notice how the variable names in the timetable created by varfun include the name of the function used. It is useful to track the operations that have been performed on the original data. Adjust the variable names back to their original values using dot notation.

pos.Properties.VariableNames = varNames;

%
% Below we plot the 3 components of the velocity and position for the time interval of interest.

figure
subplot(2,1,1)
plot(vel.Time,vel.Variables)
legend(quakeData.Properties.VariableNames,'Location','NorthWest')
title('Velocity')
subplot(2,1,2)
plot(vel.Time,pos.Variables)
legend(quakeData.Properties.VariableNames,'Location','NorthWest')
title('Position')

%
%% Visualize Trajectories
% The trajectories can be plotted in 2D or 3D by using the component value. In the following we will show different ways of visualizing this data.
% Begin with 2-dimensional projections. Here is the first with a few values of time annotated.

figure
plot(pos.NorthSouth,pos.Vertical)
xlabel('North-South')
ylabel('Vertical')
% Select locations and label
nt = ceil((max(pos.Time) - min(pos.Time))/6);
idx = find(fix(pos.Time/nt) == (pos.Time/nt))';
text(pos.NorthSouth(idx),pos.Vertical(idx),char(pos.Time(idx)))

%
% Use plotmatrix to visualize a grid of scatter plots of all variables against one another and histograms of each variable on the diagonal. The output variable Ax, represents each axes in the grid and can be used to identify which axes to label using xlabel and ylabel.

figure
[S,Ax] = plotmatrix(pos.Variables);

for ii = 1:length(varNames)
    xlabel(Ax(end,ii),varNames{ii})
    ylabel(Ax(ii,1),varNames{ii})
end

%
% Plot a 3-D view of the trajectory and plot a dot at every tenth position point. The spacing between dots indicates the velocity.

step = 10;
figure
plot3(pos.NorthSouth,pos.EastWest,pos.Vertical,'r')
hold on
plot3(pos.NorthSouth(1:step:end),pos.EastWest(1:step:end),pos.Vertical(1:step:end),'.')
hold off
box on
axis tight
xlabel('North-South')
ylabel('East-West')
zlabel('Vertical')
title('Position')

%
%% Supporting Functions
% Functions are defined below.
%

function y = velFun(x)
    y = (1/200)*cumsum(x);
    y = y - mean(y);
end

% Copyright 2012 The MathWorks, Inc.