%% Lab 7 -- Etch-a-Sketch time
%% Etch a Sketch
% As discussed in the Pre-Lab, we are working with an Etch a Sketch. The left knob moves the tracer up and down, and the right knob moves the tracer left and right.
%% Exercise 1
% Suppose your tracer starts at position (0,1). You apply the following sequence of moves of the knobs.
% Turn the right knob at 2 units per second for 2 seconds.
% Turn the left knob at -1 units per second for 1 second.
% Turn the two knobs together. The left knob at 1 unit per second, and the right knob at -1 unit per second, for 2 seconds.
% Sketch the resulting trace. Compute the distance travelled by the tracer.
%
%% Exercise 2
% Now imagine you installed measurement devices on the two knobs, so that every 1/10 of a second it reports to you the instantaneous turning speed of the knobs, measured in "units per second". The data is reported to you as
% \frac{\Delta y_1}{\Delta t}, \frac{\Delta y_2}{\Delta t}, \frac{\Delta y_3}{\Delta t}, \ldots \frac{\Delta y_N}{\Delta t}   for the 1st through Nth measurements from the left knob, and
% \frac{\Delta x_1}{\Delta t}, \frac{\Delta x_2}{\Delta t}, \frac{\Delta x_3}{\Delta t}, \ldots, \frac{\Delta x_N}{\Delta t} for the 1st through Nth measurements from the right knob.
% If the tracer starts the journey at the coordinate (0,0), write a formula approximating where it ends up after the Nth measurement. (Pay attention to units!) (You are encouraged to try to express this using Sigma notation.)
% Write also a formula approximating the total distance traveled over the course of these N measurements. (You are also encouraged to try to express this using Sigma notation.)
%% Exercise 3
% Why is it that the formulas you found for Exercise 2 only give approximately the coordinate/distance after N measurements? (Why is the value not exact?)
%
% Before continuing, check with your TA to make sure you got the correct formulas for Exercise 2.
%
%% Racing a Corvette
% Now let's apply some of what you did in Exercises 1-3 to analyzing some real life data.
% The data we will be looking at comes from the Revs Vehicle Dynamics Database, made available by JC Kegelman and JC Gerdes. Specifically we are looking at the data from the 2013 Monterey Motorsports Reunion at Laguna Seca. Our data consists of 15 minutes worth of velocity recordings of a 1963 Corvette Grand Sport speeding along the race-track at up to 120 miles per hour. (The data has been released under the Open Data Commons Attribution License, which covers our use.)
%% Load the data
% Before running the code below, make sure that the "Current Folder" pane in MATLAB (usually on your left, unless you customized the layout) is pointing to the folder where you placed the Lab7_CorvetteFinal.csv file that you downloaded for this lab.
% Run the code below to load the data.

% Set data options
opts = delimitedTextImportOptions("NumVariables", 3);

% Specify range and delimiter
opts.DataLines = [3, Inf];
opts.Delimiter = ",";

% Specify column names and types
opts.VariableNames = ["time", "vNorth", "vEast"];
opts.VariableTypes = ["double", "double", "double"];
opts.ExtraColumnsRule = "ignore";
opts.EmptyLineRule = "read";

% Import the data
CorvetteTable = readtable("Lab7_CorvetteFinal.csv", opts)

% Clear the data options
clear opts;

% As you can see in the table to the right, the data has three columns. The first column is time, this is measured in seconds from the start of the session. Our first entry is 1150 seconds into the session. We see that the table has 90,000 rows, meaning that 90,000 measurements were taken. Over 15 minutes this means that the data here are taken every 1/100 of a second.
% The second column is vNorth, which represents in meters per second the speed of the vehicle in the North-South direction (North is positive). The third column is vEast, which represents, again in meters per second the speed of the vehicle in the East-West direction (East is positive).
% We will adopt the usual cartographic bias and put North pointing up. So the North-South direction is the y direction, and the East-West direction is the x direction. Also, a convenient mnemonic device is that if you multiply by 2.2 the meters per second measurement, you will get approximately the equivalent speed measured in miles per hour. So 50 meters per second is roughly 110 miles per hour.
% For doing our analysis it is helpful to extract the two columns corresponding to the velocities.

vNorth = table2array(CorvetteTable(:,'vNorth'));
vEast = table2array(CorvetteTable(:,'vEast'));
times = table2array(CorvetteTable(:,'time'));

% For data like this it is best to visualize them in graphs

% Plot the velocity in the North (y) direction
plot(times, vNorth)

% Plot the velocity in the East (x) direction
plot(times, vEast)

% Because the car is going around on a race track, you see that the velocities are periodic. The data is not completely periodic because it also includes an initial period where the driver started to ramp up the speed, and a final period where the car is slowing down.
%
%% What does the track look like?
% What we have is the velocity data. You should think of vNorth and vEast being like the inputs you put on the two knobs of the Etch-a-Sketch. To convert this to position data we have to add up the changes.
% On each 1/100 second interval, the car moves a distance
% vNorth \times \frac{1}{100} meters to the North
% and
% vEast \times \frac{1}{100} meters to the East.
% If we add up these small distances, we can recover the position of the car.
% (Mathematically, this says that to recover the y position we just need to integrate \frac{dy}{dt}, the derivative, with is the velocity in the y direction.)
% Recall that the cumsum function returns the cumulative sum of an array, and is basically the equivalent of the indefinite integral.

posNorth = cumsum(vNorth / 100); % Finds the y coordinates of the car, measured in meters
posEast = cumsum(vEast / 100); % Finds the x coordinates of the car, measured in meters

% Notice that the posNorth really is a y position as a function of time, and posEast really is a x position as a function of time. In other words, together they described a parametrized curve. Let us visualize the curve below.

% This allows us to visualize y(t), x(t), and the curve (x(t),y(t)) all for
% the same interval of t
% The time here are measured in units of 1/100 of a second
% You can specify which interval of time you want to examine by
% setting the FirstEntry and FinalEntry variables. 
% (Make sure to set FirstEntry < FinalEntry.)
FirstEntry = 1
FinalEntry = 89999

% Plot y(t) in red, and x(t) in blue, against the time t.
plot(times(FirstEntry:FinalEntry), posNorth(FirstEntry:FinalEntry), 'r')
hold on;
plot(times(FirstEntry:FinalEntry), posEast(FirstEntry:FinalEntry), 'b')
hold off;

% Plot the curve (x(t),y(t))
plot(posEast(FirstEntry:FinalEntry), posNorth(FirstEntry:FinalEntry))

%% Exercise 4
% Based on the plots above, how many laps did the Corvette do on the tracks? Is the Corvette going clockwise or counterclockwise? Using the sliders in the code above, estimate the entry numbers for when the car returned to its starting position. For example, the first time the car returns to the starting position is approximately at the 15800th entry (you can set the variable FirstEntry to 1 and FinalEntry to 15800 to double check.)
%% Exercise 5
% In this exercise you will try to estimate the total length of the race track. You will
% use the formula from the third part of exercise 2 for computing distances traveled.
% remember that to square the velocity you need to use the . operator, as in vNorth.^2
% Use that to sum between the mth and nth entries of an array, you can use the sum function of MATLAB like so: sum(nameOfArray(m:n))
% It is a good idea to compute the lengths of the track based on several complete laps, and taking the average.

% Use this block to help you answer exercise 5
% Before summing, it may be helpful to write down a formula for the terms
% you are trying to sum

% arrayToSum = ......

% Sum the array between selected first and final entries, that represent
% the car going around the track once. 

% sum(arrayToSum(...:...))

%
%% Some Final Foods For Thought
% The almost, but not quite periodic velocities of the car should indicate to you something important about the parametrized curves: the same curve can be expressed as the graph of (x(t), y(t)) in many different ways. (Just imaging the race car driving the track at different speeds, the corresponding x(t) and y(t) will be different.
% The positions x(t) and y(t) can be obtained as an integral of the velocities x'(t) and y'(t). You will learn that the "arc length" of a parametrized curve can also be obtained as some integral of some formula depending on x'(t) and y'(t). The two formulas are not the same! The integral appears in two different ways.
% Calculus can also be used to find the area enclosed by the race track! This is something you will/may learn about in Calc III.

Area = 0.01 * sum(posEast(1:15800) .* vNorth(1:15800))  
% The area encircled by the race track, measured in square meters