MIE301 – Lab 1
Part 1: Python & Spyder Setup
This document walks you through setting up Python in Spyder and introduces the plotting and
animation functions you will need for this lab.
1. Getting Started in Spyder
On the ECF lab computers, launch Spyder from the Anaconda Navigator, or search for "Spyder" in the
Start menu. Spyder has three main panels: a script editor on the left where you write code, a Plots pane
and Variable Explorer on the right, and a console at the bottom where code actually runs and where you
can try things out interactively.
2. Turn on Animated Plots (do this once)
By default, Spyder shows plots as static images inline in the Plots pane, which will not animate. Switch it
to a live plot window before starting:
Tools → Preferences → IPython console → Graphics
Set Backend to Automatic (or "Qt5")
Click OK, then restart the IPython console (the restart icon in the console pane)
Without this step, the mechanism animations will not display frame-by-frame.
3. Opening and Running Scripts
Scripts for this lab are split into cells using # %%. This lets you run one part of the script at a time instead
of the whole file at once.
Click inside a cell and press Ctrl+Enter (Cmd+Return on Mac) to run just that cell.
Press F5 (or the green Run arrow) to run the entire file from top to bottom.
plt.pause(0.1) is what pauses briefly between animation frames — you will see this inside loops.
4. Python Plotting & Animation Basics
Every script in this lab starts with two imports:
import numpy as np
import matplotlib.pyplot as plt
numpy handles arrays and math (cos, sin, sqrt, pi, and so on) and works elementwise: if you pass it a list
of angles, you get back a list of results. matplotlib.pyplot handles all the plotting.
Building an array of values
1
np.arange(0, 10, 2)
np.linspace(0, 10, 6)
included
# 0, 2, 4, 6, 8 (stops BEFORE reaching 10)
# 6 evenly spaced points from 0 to 10, both ends
A common pattern in this lab is stepping through an angle from 0 to some maximum in fixed
increments:
stepsize = 30 * np.pi / 180
# 30 degrees, in radians
theta2 = np.arange(0, max_angle + stepsize / 2, stepsize)
# the "+ stepsize / 2" is just a safety margin so the last point isn't dropped
Creating a figure and drawing on it
fig, ax = plt.subplots()
# creates a figure with one set of axes, "ax"
Once you have ax, everything is drawn by calling methods on it:
Function
What it does
ax.plot(x, y, 'ro')
Plots points/lines. The string sets color and
marker — 'r' = red, 'o' = circle, '--' = dashed
line, 'g' = green, 'b' = blue.
ax.plot(x, y, color='r', linewidth=3)
Same as above, using named keyword
arguments instead of a format string.
ax.set_xlabel('x (cm)', fontsize=15)
Labels the x-axis. set_ylabel works the same
way for the y-axis.
ax.set_title('...')
Sets the plot title.
ax.grid(True)
Turns on the background grid.
ax.set_aspect('equal')
Makes one unit on x equal one unit on y, so
shapes aren't stretched.
ax.set_xlim(xmin, xmax)
Sets the visible x-axis range. set_ylim does
the same for y.
ax.text(x, y, 'B', color='b')
Places a text label at a given point.
ax.add_patch(Rectangle((x, y), w, h,
fill=False))
Draws a rectangle (needs: from
matplotlib.patches import Rectangle first).
ax.legend()
Shows a legend. Give each plot a label='...'
when you create it, and legend() will pick
those up automatically.
2
ax.cla()
Clears everything drawn on the axes so far —
used to erase the previous frame before
drawing the next one.
plt.pause(0.1)
Pauses briefly and redraws the figure — this
is what makes an animation visible frame by
frame.
One thing to know: calling ax.plot() more than once does not erase what was plotted before — each
new call adds to the same axes. That is what lets you build up a drawing (base pivot, then link, then
labels, then a rectangle) with several plot calls in a row.
The animation pattern
A mechanism is animated by looping over each angle, drawing the mechanism at that angle, then
pausing briefly before the next frame:
for i in range(len(theta2)):
ax.cla()
# clear the previous frame
ax.plot(...)
# draw the mechanism at this configuration
plt.pause(0.1)
# pause, then move to the next frame
If you want several configurations to stay on screen at once instead of animating (for example, showing
5 positions of the mechanism on one static plot), just leave out ax.cla() — each new ax.plot() call will add
to what is already there instead of erasing it.
3
Part 2: Prelab - Introduction to Python Using Spyder
Steps: The TA will guide you through these steps at the beginning of the Practical.
1. Lay out your Spyder environment: Editor, IPython Console, Variable Explorer, Plots, Files, etc.
2. Run some commands from the Spyder “IPython Console.”
3. Create a new scalar a = 5. See it appear in the “Variable Explorer” list of variables.
4. Create a vector of integers b from 1 to 10 using NumPy's arange() function.
5. Erase all variables in the Variable Explorer using %reset -f.
6. Unlike MATLAB, Python does not require a semicolon to suppress the output of an assignment.
Create a vector c containing the integers from 1 to 40 and assign it to a variable without
displaying its contents.
7. Clear the IPython Console using %clear or Ctrl+L.
8. Access the last 10 elements of c using Python array slicing. Remember that Python uses zerobased indexing.
9. Create a vector time with steps of 0.1 seconds, from 0 to 4 seconds, using NumPy's arange() or
linspace() function.
10. Obtain the size of the vector time using len(time). You can also inspect the dimensions of a
NumPy array using its shape attribute.
11. Create a new figure using Matplotlib. Depending on your Spyder settings, the figure will appear
in the “Plots” pane or in a separate window.
12. Plot sin(time) versus time using Matplotlib's plot() function.
13. Change the datapoint style so that the data are displayed using red circle markers. Matplotlib
supports formatting strings similar to MATLAB, including 'ro'.
14. Add the title “my test plot” to the figure and set the font size to 15.
15. Add an x-axis label “time (sec)” and a y-axis label “sin(t)”, both with a font size of 15.
16. Add a grid to the figure.
17. Clear the current figure and plot cos(time) versus time, in blue with x-shaped datapoint
markers. Notice that the previous data disappear after the figure or axes are cleared.
4
18. Plot tan(time) in red on top of cos(time) so that both are visible in the figure. Unlike MATLAB,
Matplotlib normally retains existing plotted lines, so an equivalent to MATLAB's hold on is
generally unnecessary. Add a legend to distinguish the two curves.
19. Close the figure and create a new figure consisting of two vertically arranged subplots. In the
first subplot, create x with 100 evenly spaced points from 0 to 10 and plot sin(x). In the second
subplot, plot sin(5x) using the same values of x.
5
Part 3: The Lab
Due: One week after your assigned lab session on Quercus at 4 pm.
Example: for lab session on Thursday, the submission due time is next Thursday at 4 pm. Penalty will be
given for late submission.
Before starting this lab, you must complete the pre-lab review sheet. During your Practical computer lab,
the TA will go through this pre-lab as a brief introduction to using Python.
--------------------------------------------------------------------This introductory Python programming problem will cover basic calculations and visualization of
mechanism motion in an animated and printed form. You will visualize the motion of two simple
mechanisms.
Report:
Labeled figures and answers to parts a-e, following the report template.
Submission:
Upload to the following files directly to Quercus:
report.pdf lab1_case1.py lab1_case2.py
Note: lab1_case1.py and lab1_case2.py should include all the Python code that you use to answer the
questions and generate the figures for each case. The Python files should be clearly annotated, runnable
cell-by-cell, and report no errors without any modification by the TA. Penalty will be given if nonexecutable code is submitted.
--------------------------------------------------------------------The given code (Lab1_starter.py file on Quercus) simulates the rotation of a single link (link 2) about a
fixed pivot (point O). In this assignment you will add to the code to simulate the two cases shown below.
In case1, link 3 hangs free under the influence of gravity. In case 2, the link 2 is extended out to point C
with a rigid connection. There is a motor at the base of link 2 which rotates link 2 at a constant rate.
6
Report deliverables: Labelled figures and answers to parts a)-e)
a) Two figures (one figure for each case) showing the mechanism in the final configuration (𝜃 =
300°), with the path of points B and C traced out from initial to final configuration.
b) The same motion from part a) but this time, include 5 configurations ( 𝜃 =
0°, 75°, 150°, 225°, 300° ) on the figure to visualize the motion like in this image.
c) For each case, use only N=6 equal-distanced data points ( 𝜃 = 0°, 60°, 120°, 180°, 240°, 300° ) to
plot the path of points B and C. Repeat with N=11 and N=21.
Compare the figures with what you got with part a) and answer this question: how many datapoints
are needed to get a good approximation of the motion and why?
d) Answer this question: what is the shape of the path traced out by point C in each case?
e) Answer this question: in case1, the angle between the two links is a function of 𝜃 . Derive a
formula for this angle.
𝜃 should rotate from 0 to 300°.
In case 1, link 2 should be 3 cm long, while link 3 is 2 cm.
In case 2, the OB segment is 3 cm long and the segment BC is 2 cm.
The constant angle ϕ should be equal to the last two digits of your student # in degrees (tell us what
that number is in your report).
For case1, draw the mass at C as a box using ax.add_patch(Rectangle(...)) (see Part 1).
All points and curves should be labelled. You can do this with ax.text() (see Part 1).
Hints:
Place the coordinate origin at point A with positive x direction to the right and positive y direction
upwards.
To draw point C in case2, calculate the x and y coordinates of point C using trigonometry. Start
from point B.
Try the command axis equal
Feeling confident? (optional advanced problem): make a third figure for a mechanism similar to case1, but
with a motor at point B which rotates link 3 at a constant rate 65% that of 𝜃̇ . Draw the stick diagram and
include the plot of motion.
Marking Rubric:
7
2 pt
Report is clearly organized
2 pt
Figures are properly formatted, with labels and units
4 pt
Motion plotted is correct and shows what we asked for
2 pt
Answer to questions