A Really Quick Introduction to Programming

January 5, 2018

With examples using python.

• Statement: A command given to the computer.
• Assign a value of -9.8 to a variable called “g”:
• g = -9.8
• Print the value of “g” to the screen:
• print g
• Variable: A placeholder name used to record data for later use. In the first statement above, g, is a variable and it is assigned a value of -9.8. Variable names in python start with a letter or underscore “_”. Variables can hold different types of data, for example:
• strings:
• x = "hello"
• Floating point number (aka. a float):
• x = 9.8
• Integer:
• x = 5
• True/False (aka boolean):
• x = True
• Operations: Statements where some sort of calculation is made:
• Add two numbers and assign the result to a variable called “y”:
• y = 3 + 5
• Divide the value in the variable “y” by 2 and then assign the value to another variable called “z”:
• z = y / 2
• Operators: The symbols that tell what operation to do:
• + – * / are used for addition, subtraction, multiplication, and division respectively
• ** is used for exponents so 5 squared (52) is:
• a = 5**2
• Loops: Tell the computer to do something over and over again. There are different types:
• “For” loops are good for doing things a set number of times
• for i in range(5):
print i

results in:

0
1
2
3
4

• Logical statements: These test to see if something is True or False and then do different things based on the outcome:
• Assign a value to a variable called “x”, check to see if the value is greater than 10, and print out a different sentence based on the result:
• x = 12
if (x > 10):
print "x is greater than 10"
else:
print "x is less than 10"
• Functions: Chunks of code that someone (maybe even you) wrote that can be referenced via a shortcut:
• Create a function to calculate the force of gravity at the Earth’s surface if you give it a mass:

def forceOfGravity(mass):
Fg = mass * -9.8
return Fg

Call the function to find the force of gravity acting on a mass of 100 kg and print out the result:

x = forceOfGravity(100)
print x

the result should be:

-980
• Classes: A class is like a function that you can assign to a variable and then have it do a lot more stuff.
• In vpython there is a class called “sphere”. It renders a 3d sphere on the screen. Here we’ll create a sphere, assign it to a variable “ball” and then change one of its built-in properties, the color, from the default (white) to red. (if you are using Glowscript.org then don’t use the first line that imports the visual module).

from visual import *
ball = sphere()
ball.color = color.red

Citing this post: Urbano, L., 2018. A Really Quick Introduction to Programming, Retrieved April 21st, 2018, from Montessori Muddle: http://MontessoriMuddle.org/ .
Attribution (Curator's Code ): Via: Montessori Muddle; Hat tip: Montessori Muddle.

Hour of Code

December 4, 2017

We are trying the Hour of Code today. Updates to follow.

Citing this post: Urbano, L., 2017. Hour of Code, Retrieved April 21st, 2018, from Montessori Muddle: http://MontessoriMuddle.org/ .
Attribution (Curator's Code ): Via: Montessori Muddle; Hat tip: Montessori Muddle.

Generating 3d Terrain

June 29, 2017

3d model of the Hawaiian island chain, rendered in OpenSCAD.

After a lot of hours of experimentation I’ve finally settled on a workable method for generating large-scale 3d terrain.

Data from the NGDC’s Grid Extraction tool. The ETOPO1 (bedrock) option gives topography and bathymetry. You can select a rectangle from a map, but it can’t be too big and, which is quite annoying, you can’t cross the antimeridian.

The ETOPO1 data is downloaded as a GeoTIFF, which can be easily converted to a png (I use ImageMagick convert).

The Hawaiian data with the downloaded grayscale.

Adjusting the color scale. One interesting property of the data is that it uses a grayscale to represent the elevations that tops out at white at sea-level, then switches to black and starts from there for land (see the above image). While this makes it easy to see the land in the image, it needs to be adjusted to get a good heightmap for the 3d model. So I wrote a python script that uses matplotlib to read in the png image as an array and then I modify the values. I use it to output two images: one of the topography and one of just land and water that I’ll use as a mask later on.

Hawaiian Islands with adjusted topography and ocean-land.

The images I export using matplotlib as grayscale png’s, which can be opened in OpenSCAD using the surface command, and then saved as an stl file. Bigger image files are take longer. A 1000×1000 image will take a few minutes on my computer to save, however the stl file can be imported into 3d software to do with as you will.

Note: H.G. Deitz has a good summary of free tools for Converting Images Into OpenSCAD Models

Citing this post: Urbano, L., 2017. Generating 3d Terrain, Retrieved April 21st, 2018, from Montessori Muddle: http://MontessoriMuddle.org/ .
Attribution (Curator's Code ): Via: Montessori Muddle; Hat tip: Montessori Muddle.

Go Board

March 29, 2017

Students playing Go.

I recently discovered that, although they may look it, Go boards are not necessarily square. They’re slightly longer in one dimension so that the board looks more square to the players on both sides.

A student asked me to make one for him–he’d ordered a set recently and didn’t like the board it came with–so, I wrote a small python program to generate the Go grid, then lasered it onto a nice piece of sanded plywood.

It worked out quite well. Apparently the plywood makes just the right “thunk” sound when you put down the pieces.

Go board in use.

The script to generate the grid.
go_board_2.py

from visual import *
from svgInator_3 import *

length = 424.2  #mm
width = 454.5   #mm
nLines = 19
dx = length/(nLines-1)
dy = width/(nLines-1)

print "Lenght = ", length
print "dx = ", dx

f = svgInator("go_board.svg")

lineStyle = {"stroke": "#000", "stroke-width": "2pt",}

#lines
for i in range(nLines):
x = i * dx
y = i * dy
#vertical
f.line(pos=[vector(x,0), vector(x,width)], style=lineStyle)
#horizontal
f.line(pos=[vector(0,y), vector(length,y)], style=lineStyle)

#circles
grid_pos = [(3,3), (3,9), (3,15),
(9,3), (9,9), (9,15),
(15,3), (15,9), (15,15)]

for i in grid_pos:
(x, y) = (i[0]*dx, i[1]*dy)
style={"stroke": "#000", "fill":"#000"})

#bounding box
f.rect(dim=vector(length,width), style=lineStyle)

f.close()


Now I just have to learn to play.

Citing this post: Urbano, L., 2017. Go Board, Retrieved April 21st, 2018, from Montessori Muddle: http://MontessoriMuddle.org/ .
Attribution (Curator's Code ): Via: Montessori Muddle; Hat tip: Montessori Muddle.

Modeling Earth’s Energy Balance (Zero-D) (Transient)

February 23, 2017

Temperature change over time (in thousands of years). As the Earth warms from 3K to equilibrium.

If the Earth behaved as a perfect black body and absorbed all incoming solar radiation (and radiated with 100% emissivity) the we calculated that the average surface temperature would be about 7 degrees Celsius above freezing (279 K). Keeping with this simplification we can think about how the Earth’s temperature could change with time if it was not at equilibrium.

If the Earth started off at the universe’s background temperature of about 3K, how long would it take to get up to the equilibrium temperature?

Using the same equations for incoming solar radiation (Ein) and energy radiated from the Earth (Eout):

$E_{in} = I \times \pi (r_E)^2$

$E_{out} = \sigma T^4 4 \pi r_{E}^2$

Symbols and constants are defined here except:

• rE = 6.371 x 106 m

At equilibrium the energy in is equal to the energy out, but if the temperature is 3K instead of 279K the outgoing radiation is going to be a lot less than at equilibrium. This means that there will be more incoming energy than outgoing energy and that energy imbalance will raise the temperature of the Earth. The energy imbalance (ΔE) would be:

$\Delta E = E_{in}-E_{out}$

All these energies are in Watts, which as we’ll recall are equivalent to Joules/second. In order to change the temperature of the Earth, we’ll need to know the specific heat capacity (cE) of the planet (how much heat is required to raise the temperature by one Kelvin per unit mass) and the mass of the planet. We’ll approximate the entire planet’s heat capacity with that of one of the most common rocks, granite. The mass of the Earth (mE) we can get from NASA:

• cE = 800 J/kg/K
• mE = 5.9723×1024kg

So looking at the units we can figure out the the change in temperature (ΔT) is:

$\Delta T = \frac{\Delta E \Delta t}{c_E m_E}$

Where Δt is the time step we’re considering.

Now we can write a little program to model the change in temperature over time:

EnergyBalance.py

from visual import *
from visual.graph import *

I = 1367.
r_E = 6.371E6
c_E = 800.
m_E = 5.9723E24

sigma = 5.67E-8

T = 3                               # initial temperature

yr = 60*60*24*365.25
dt = yr * 100
end_time = yr * 1000000
nsteps = int(end_time/dt)

Tgraph = gcurve()

for i in range(nsteps):
t = i*dt
E_in = I * pi * r_E**2
E_out = sigma * (T**4) * 4 * pi * r_E**2
dE = E_in - E_out
dT = dE * dt / (c_E * m_E)
T += dT
Tgraph.plot(pos=(t/yr/1000,T))
if i%10 == 0:
print t/yr, T
rate(60)



The results of this simulation are shown at the top of this post.

What if we changed the initial temperature from really cold to really hot? When the Earth formed from the accretionary disk of the solar nebula the surface was initially molten. Let’s assume the temperature was that of molten granite (about 1500K).

Cooling if the Earth started off molten (1500K). Note that this simulation only runs for 250,000 years, while the warming simulation (top of page) runs for 1,000,000 years.

Citing this post: Urbano, L., 2017. Modeling Earth's Energy Balance (Zero-D) (Transient), Retrieved April 21st, 2018, from Montessori Muddle: http://MontessoriMuddle.org/ .
Attribution (Curator's Code ): Via: Montessori Muddle; Hat tip: Montessori Muddle.

Modeling Earth’s Energy Balance (Zero-D) (Equilibrium)

February 22, 2017

For conservation of energy, the short-wave solar energy absorbed by the Earth equals the long-wave outgoing radiation.

Energy and matter can’t just disappear. Energy can change from one form to another. As a thrown ball moves upwards, its kinetic energy of motion is converted to potential energy due to gravity. So we can better understand systems by studying how energy (and matter) are conserved.

Energy Balance for the Earth

Let’s start by considering the Earth as a simple system, a sphere that takes energy in from the Sun and radiates energy off into space.

Incoming Energy

At the Earth’s distance from the Sun, the incoming radiation, called insolation, is 1367 W/m2. The total energy (wattage) that hits the Earth (Ein) is the insolation (I) times the area the solar radiation hits, which is the area a cross section of the Earth (Acx).

$E_{in} = I \times A_{cx}$

Given the Earth’s radius (rE) and the area of a circle, this becomes:

$E_{in} = I \times \pi (r_E)^2$

Outgoing Energy

The energy radiated from the Earth is can be calculated if we assume that the Earth is a perfect black body–a perfect absorber and radiatior of Energy (we’ve already been making this assumption with the incoming energy calculation). In this case the energy radiated from the planet (Eout) is proportional to the fourth power of the temperature (T) and the surface area that is radiated, which in this case is the total surface area of the Earth (Asurface):

$E_{out} = \sigma T^4 A_{surface}$

The proportionality constant (σ) is: σ = 5.67 x 10-8 W m-2 K-4

Note that since σ has units of Kelvin then your temperature needs to be in Kelvin as well.

Putting in the area of a sphere we get:

$E_{out} = \sigma T^4 4 \pi r_{E}^2$

Balancing Energy

Now, if the energy in balances with the energy out we are at equilibrium. So we put the equations together:

$E_{in} = E_{out}$

$I \times \pi r_{E}^2 = \sigma T^4 4 \pi r_{E}^2$

cancelling terms on both sides of the equation gives:

$I = 4 \sigma T^4$

and solving for the temperature produces:

$T = \sqrt{\frac{I}{4 \sigma}}$

Plugging in the numbers gives an equilibrium temperature for the Earth as:

T = 278.6 K

Since the freezing point of water is 273K, this temperature is a bit cold (and we haven’t even considered the fact that the Earth reflects about 30% of the incoming solar radiation back into space). But that’s the topic of another post.

Citing this post: Urbano, L., 2017. Modeling Earth's Energy Balance (Zero-D) (Equilibrium), Retrieved April 21st, 2018, from Montessori Muddle: http://MontessoriMuddle.org/ .
Attribution (Curator's Code ): Via: Montessori Muddle; Hat tip: Montessori Muddle.

Projectile Paths

January 10, 2017

Paths of a projectile.

I had my Numerical Methods student calculate the angle that would give a ballistic projectile its maximum range, then I had them write a program that did the the same by just trying a bunch of different angles. The diagram above is what they came up with.

It made an interesting pattern that I converted into a face-plate cover for a light switch that I made using the laser at the TechShop.

Face plate cover.

Citing this post: Urbano, L., 2017. Projectile Paths, Retrieved April 21st, 2018, from Montessori Muddle: http://MontessoriMuddle.org/ .
Attribution (Curator's Code ): Via: Montessori Muddle; Hat tip: Montessori Muddle.

Sorting algorithms (with Hungarian Dance)

November 29, 2016

This TedEd video explains a few common sorting methods used in computer science. Sorting can be a challenging computational problem because of the enormous number of comparisons between items that can be involved, so computer scientists has spent a lot of time looking into it.

The video below shows the Quick Sort method using Hungarian folk dance.

Citing this post: Urbano, L., 2016. Sorting algorithms (with Hungarian Dance), Retrieved April 21st, 2018, from Montessori Muddle: http://MontessoriMuddle.org/ .
Attribution (Curator's Code ): Via: Montessori Muddle; Hat tip: Montessori Muddle.