Difference between revisions of "MAP:Cantilever Beam"

From PrattWiki
Jump to navigation Jump to search
 
(17 intermediate revisions by the same user not shown)
Line 1: Line 1:
The Cantilever Beam lab has been a foundation of EGR 103 for several years.  It demonstrates how to initialize the workspace, load and manipulate data, perform calculations, generate values of a model equation, plot data and model values, and save plots.  Not bad for the second week of an introductory course in computational methods!  For at least the short-term, the Cantilever Beam lab will live on in MATLAB and in Python.  Since the lab itself actually develops the final code, it is acceptable to post it here.  Here's what the lab's solution looks like in MATLAB and in Python 3:
+
The Cantilever Beam lab has been a foundation of EGR 103 for several years.  It demonstrates how to initialize the workspace, load and manipulate data, perform calculations, generate values of a model equation, plot data and model values, and save plots.  Not bad for the second week of an introductory course in computational methods!  For at least the short-term, the Cantilever Beam lab will live on in MATLAB and in Python.  Since the lab itself actually develops the final code, it is acceptable to post it here.  Here's what the lab's solution looks like in MATLAB and in Python 3.  There are two Python versions - the first is a more object-oriented approach and the second is a more state-machine approach.
  
 
== MATLAB ==
 
== MATLAB ==
<source lang='matlab'>
+
<syntaxhighlight lang='matlab' line='line'>
 
%% Initialize the workspace
 
%% Initialize the workspace
 
% Clear all variables
 
% Clear all variables
Line 11: Line 11:
 
%% Load and manipulate the data
 
%% Load and manipulate the data
 
% Load data from Cantilever.dat
 
% Load data from Cantilever.dat
load Cantilever.dat
+
beam_data = load('Cantilever.dat')
 
% Copy data from each column into new variables
 
% Copy data from each column into new variables
Mass = Cantilever(:,1);
+
mass  = beam_data(:,1);
Displacement = Cantilever(:,2);
+
displ = beam_data(:,2);
% Convert Mass to a Force measurement
+
% Convert mass to a force measurement
Force = Mass*9.81;
+
force = mass*9.81;
% Convert Displacement in inches to meters
+
% Convert displacement in inches to meters
Displacement = (Displacement*2.54)/100;
+
displ = (displ*2.54)/100;
  
 
%% Perform calculations
 
%% Perform calculations
 
% Use polyfit to find first-order fit polynomials
 
% Use polyfit to find first-order fit polynomials
P = polyfit(Force, Displacement, 1)
+
P = polyfit(force, displ, 1)
  
 
%% Generate predictions
 
%% Generate predictions
% Create 100 representational Force values
+
% Create 100 representational force values
ForceModel = linspace(min(Force),max(Force),100);
+
force_model = linspace(min(force),max(force),100);
 
% Calculate Displacement predictions
 
% Calculate Displacement predictions
DispModel = polyval(P, ForceModel);
+
disp_model = polyval(P, force_model);
  
 
%% Generate and save plots
 
%% Generate and save plots
Line 36: Line 36:
 
clf
 
clf
 
% Plot Displacement as a function of Force
 
% Plot Displacement as a function of Force
plot(Force, Displacement, 'ko')
+
plot(force, displ, 'ko')
 
% Turn hold on, plot the model values, and turn hold off
 
% Turn hold on, plot the model values, and turn hold off
 
hold on
 
hold on
plot(ForceModel, DispModel, 'k-')
+
plot(force_model, disp_model, 'k-')
 
hold off
 
hold off
 
% Turn the grid on
 
% Turn the grid on
Line 47: Line 47:
 
ylabel('Displacement (meters)')
 
ylabel('Displacement (meters)')
 
title('Displacement vs. Force for Cantilever.dat (NetID)')
 
title('Displacement vs. Force for Cantilever.dat (NetID)')
% Save the graph to PostScript
+
% Save the graph to PostScript and PDF
 
print -deps RunCanPlot
 
print -deps RunCanPlot
</source>
+
print -dpdf RunCanPlot
 +
</syntaxhighlight >
  
 
== Python ==
 
== Python ==
<source lang=python>
+
=== More Pythonic ===
 +
<syntaxhighlight lang=python line='line'>
 
# %% Import modules
 
# %% Import modules
 
import numpy as np
 
import numpy as np
Line 63: Line 65:
 
mass = beam_data[:, 0].copy()
 
mass = beam_data[:, 0].copy()
 
disp = beam_data[:, 1].copy()
 
disp = beam_data[:, 1].copy()
# Convert Mass to a Force measurement
+
# Convert mass to a force measurement
 
force = mass * 9.81
 
force = mass * 9.81
# Convert Displacement in inches to meters
+
# Convert displacement in inches to meters
 
disp = (disp * 2.54) / 100.0
 
disp = (disp * 2.54) / 100.0
  
Line 71: Line 73:
 
# Use polyfit to find first-order fit polynomials
 
# Use polyfit to find first-order fit polynomials
 
p = np.polyfit(force, disp, 1)
 
p = np.polyfit(force, disp, 1)
 +
print(p)
 +
 +
# %% Generate predictions
 +
# Create 100 representational force values
 +
force_model = np.linspace(min(force), max(force), 100)
 +
# Calculate displacement predictions
 +
disp_model = np.polyval(p, force_model)
 +
 +
# %% Generate and save plots
 +
# Create a Figure and Axes
 +
fig, ax = plt.subplots(num=0, clear=True)
 +
# Plot Displacement as a function of Force
 +
ax.plot(force, disp, 'ko')
 +
# Plot the model values
 +
ax.plot(force_model, disp_model, 'k-')
 +
# Turn the grid on
 +
ax.grid(True)
 +
# Label and title the graph
 +
ax.set_xlabel('Force (Newtons)')
 +
ax.set_ylabel('Displacement (meters)')
 +
ax.set_title('Displacement vs. Force for Cantilever.dat (NetID)')
 +
# Use tight layout
 +
fig.tight_layout()
 +
# Save the graph to PostScript
 +
fig.savefig('RunCanPlot.eps')
 +
fig.savefig('RunCanPlot.pdf')
 +
 +
</syntaxhighlight>
 +
 +
=== More MATLABic ===
 +
<syntaxhighlight lang=python line='line'>
 +
# %% Import modules
 +
import numpy as np
 +
import matplotlib.pyplot as plt
 +
 +
# %% Load and manipulate the data
 +
# Load data from Cantilever.dat
 +
beam_data = np.loadtxt('Cantilever.dat')
 +
# Copy data from each column into new variables
 +
mass  = beam_data[:, 0].copy()
 +
displ = beam_data[:, 1].copy()
 +
# Convert mass to a force measurement
 +
force = mass * 9.81
 +
# Convert displace in inches to meters
 +
displ = (displ * 2.54) / 100.0
 +
 +
# %% Perform calculations
 +
# Use polyfit to find first-order fit polynomials
 +
p = np.polyfit(force, displ, 1)
  
 
# %% Generate predictions
 
# %% Generate predictions
Line 84: Line 135:
 
plt.clf()
 
plt.clf()
 
# Plot Displacement as a function of Force
 
# Plot Displacement as a function of Force
plt.plot(force, disp, 'ko')
+
plt.plot(force, displ, 'ko')
 
# Plot the model values
 
# Plot the model values
 
plt.plot(force_model, disp_model, 'k-')
 
plt.plot(force_model, disp_model, 'k-')
Line 93: Line 144:
 
plt.ylabel('Displacement (meters)')
 
plt.ylabel('Displacement (meters)')
 
plt.title('Displacement vs. Force for Cantilever.dat (NetID)')
 
plt.title('Displacement vs. Force for Cantilever.dat (NetID)')
# Save the graph to PostScript
+
# Save the graph to PostScript and PDF
 
plt.savefig('RunCanPlot.eps')
 
plt.savefig('RunCanPlot.eps')
 
plt.savefig('RunCanPlot.pdf')
 
plt.savefig('RunCanPlot.pdf')
  
</source>
+
</syntaxhighlight >
 +
 
 +
=== Embedded Example ===
 +
The following is an example using [http://trinket.io Trinket].  You can make changes to the code and then re-run it!
 +
 
 +
<html>
 +
<iframe src="https://trinket.io/embed/python3/0cb59ca6cf" width="100%" height="600" frameborder="0" marginwidth="0" marginheight="0" allowfullscreen></iframe>
 +
</html>
 +
 
 +
<!--
 +
== Mathematica ==
 +
Starting with the Summer of 2021, I have been working on moving from Maple to Mathematica as a symbolic computation language. 
 +
 
 +
=== Static View ===
 +
A static, publicly-viewable Mathematica version of this program is in the box below. If you have Mathematica on your own computer, you can download this notebook for yourself using the menu at the bottom left of the box below.
 +
<html>
 +
<iframe src="https://www.wolframcloud.com/obj/b59aa935-2740-40e6-84b0-00afaf875f8f?_embed=iframe" width="600" height="800"></iframe>
 +
</html>
 +
 
 +
=== Interactive Version ===
 +
If you have a [https://www.wolframcloud.com/ Wolfram Cloud] account (including the free basic version), you can get your own interactive version as follows:
 +
* Go to the Wolfram Cloud version via [https://www.wolframcloud.com/env/b59aa935-2740-40e6-84b0-00afaf875f8f this link].  You will not be able to change or run anything. 
 +
* In the light gray bar at the top of the notebook, go to File->Duplicate.  This will create a copy of the file in your cloud, generally in a folder called <code>Copied Files</code>
 +
* In the dark gray bar at the very top of the notebook, on the right, click on <code>Cloud Files</code> to open the Cloud Files browser on the right.  If you are already in Copied Files, stay there.  If you see a folder called Copied Files, click into it.
 +
* You will need to create a text file called <code>Cantilever.dat</code> that lives in the same folder as the notebook.  At the top of the Cloud Files browser, there should be a set of two red icons - one with a piece of paper and a plus in it and one with a down arrow.  Click the down arrow and select <code>Text</code>.
 +
* Copy the following into the blank text file that comes up:
 +
<syntaxhighlight>
 +
0.000000 0.005211
 +
0.113510002 0.158707
 +
0.227279999 0.31399
 +
0.340790009 0.474619
 +
0.455809998 0.636769
 +
0.569320007 0.77989
 +
0.683630005 0.936634
 +
0.797140015 0.999986
 +
</syntaxhighlight>
 +
* In the light gray box, click the <code>(unnamed)</code> name.  Where the <code>.txt</code> is change that to <code>Cantilever.dat</code> then click <code>Choose another directory</code>.  In the new window that comes up, double-click on the <code>Copied Files</code> icon then click the <code>Choose</code> button.  After that window goes away, click on the <code>Cantilever.dat</code> text again and hit return.
 +
-->

Latest revision as of 23:23, 28 August 2021

The Cantilever Beam lab has been a foundation of EGR 103 for several years. It demonstrates how to initialize the workspace, load and manipulate data, perform calculations, generate values of a model equation, plot data and model values, and save plots. Not bad for the second week of an introductory course in computational methods! For at least the short-term, the Cantilever Beam lab will live on in MATLAB and in Python. Since the lab itself actually develops the final code, it is acceptable to post it here. Here's what the lab's solution looks like in MATLAB and in Python 3. There are two Python versions - the first is a more object-oriented approach and the second is a more state-machine approach.

MATLAB

 1 %% Initialize the workspace
 2 % Clear all variables
 3 clear
 4 % Change display to short exponential format
 5 format short e
 6 
 7 %% Load and manipulate the data
 8 % Load data from Cantilever.dat
 9 beam_data = load('Cantilever.dat')
10 % Copy data from each column into new variables
11 mass  = beam_data(:,1);
12 displ = beam_data(:,2);
13 % Convert mass to a force measurement
14 force = mass*9.81;
15 % Convert displacement in inches to meters
16 displ = (displ*2.54)/100;
17 
18 %% Perform calculations
19 % Use polyfit to find first-order fit polynomials
20 P = polyfit(force, displ, 1)
21 
22 %% Generate predictions
23 % Create 100 representational force values
24 force_model = linspace(min(force),max(force),100);
25 % Calculate Displacement predictions
26 disp_model = polyval(P, force_model);
27 
28 %% Generate and save plots
29 % Bring up a figure window
30 figure(1)
31 % Clear the figure window
32 clf
33 % Plot Displacement as a function of Force
34 plot(force, displ, 'ko')
35 % Turn hold on, plot the model values, and turn hold off
36 hold on
37 plot(force_model, disp_model, 'k-')
38 hold off
39 % Turn the grid on
40 grid on
41 % Label and title the graph
42 xlabel('Force (Newtons)')
43 ylabel('Displacement (meters)')
44 title('Displacement vs. Force for Cantilever.dat (NetID)')
45 % Save the graph to PostScript and PDF
46 print -deps RunCanPlot
47 print -dpdf RunCanPlot

Python

More Pythonic

 1 # %% Import modules
 2 import numpy as np
 3 import matplotlib.pyplot as plt
 4 
 5 # %% Load and manipulate the data
 6 # Load data from Cantilever.dat
 7 beam_data = np.loadtxt('Cantilever.dat')
 8 # Copy data from each column into new variables
 9 mass = beam_data[:, 0].copy()
10 disp = beam_data[:, 1].copy()
11 # Convert mass to a force measurement
12 force = mass * 9.81
13 # Convert displacement in inches to meters
14 disp = (disp * 2.54) / 100.0
15 
16 # %% Perform calculations
17 # Use polyfit to find first-order fit polynomials
18 p = np.polyfit(force, disp, 1)
19 print(p)
20 
21 # %% Generate predictions
22 # Create 100 representational force values
23 force_model = np.linspace(min(force), max(force), 100)
24 # Calculate displacement predictions
25 disp_model = np.polyval(p, force_model)
26 
27 # %% Generate and save plots
28 # Create a Figure and Axes
29 fig, ax = plt.subplots(num=0, clear=True)
30 # Plot Displacement as a function of Force
31 ax.plot(force, disp, 'ko')
32 # Plot the model values
33 ax.plot(force_model, disp_model, 'k-')
34 # Turn the grid on
35 ax.grid(True)
36 # Label and title the graph
37 ax.set_xlabel('Force (Newtons)')
38 ax.set_ylabel('Displacement (meters)')
39 ax.set_title('Displacement vs. Force for Cantilever.dat (NetID)')
40 # Use tight layout
41 fig.tight_layout()
42 # Save the graph to PostScript
43 fig.savefig('RunCanPlot.eps')
44 fig.savefig('RunCanPlot.pdf')

More MATLABic

 1 # %% Import modules
 2 import numpy as np
 3 import matplotlib.pyplot as plt
 4 
 5 # %% Load and manipulate the data
 6 # Load data from Cantilever.dat
 7 beam_data = np.loadtxt('Cantilever.dat')
 8 # Copy data from each column into new variables
 9 mass  = beam_data[:, 0].copy()
10 displ = beam_data[:, 1].copy()
11 # Convert mass to a force measurement
12 force = mass * 9.81
13 # Convert displace in inches to meters
14 displ = (displ * 2.54) / 100.0
15 
16 # %% Perform calculations
17 # Use polyfit to find first-order fit polynomials
18 p = np.polyfit(force, displ, 1)
19 
20 # %% Generate predictions
21 # Create 100 representational Force values
22 force_model = np.linspace(min(force), max(force), 100)
23 # Calculate Displacement predictions
24 disp_model = np.polyval(p, force_model)
25 
26 # %% Generate and save plots
27 # Bring up a figure window
28 plt.figure(1)
29 # Clear the figure window
30 plt.clf()
31 # Plot Displacement as a function of Force
32 plt.plot(force, displ, 'ko')
33 # Plot the model values
34 plt.plot(force_model, disp_model, 'k-')
35 # Turn the grid on
36 plt.grid()
37 # Label and title the graph
38 plt.xlabel('Force (Newtons)')
39 plt.ylabel('Displacement (meters)')
40 plt.title('Displacement vs. Force for Cantilever.dat (NetID)')
41 # Save the graph to PostScript and PDF
42 plt.savefig('RunCanPlot.eps')
43 plt.savefig('RunCanPlot.pdf')

Embedded Example

The following is an example using Trinket. You can make changes to the code and then re-run it!