Antarctic Information Assignment
An overview of the task
You will write an interactive Python program that will run on a machine in the exhibition hall at the new science museum, as part of this exhibition. Your program will guide users to a better understanding and appreciation of the environment emperor penguins inhabit and how they survive these conditions.
This assignment requires you to produce the deliverable outlined below:
(D1) A Python code file that satisfies the specifications
Solution:
import math
import matplotlib.pyplot as plt
import numpy as np
# Declare the mean max and mean min temperatures per month
max_temp = [2.9, -1.6, -8.3, -11.1, -10.2, -12.5, -12.5, -10.8, -11.1, -8.3, -1.6, 1.8, 1.6]
min_temp = [-2.4, -7.4, -15.5, -17.2, -16.4, -18.4, -19.2, -17.6,-17.8, -14.5, -7.5, -4.5, -3.8]
def average_antarctic_temp(days):
"""
Calculates the average daily temperature (ºC) at that day
:param days: days since 1 Jan 2020
:return: Temperature in ºC
"""
# Given the day get the month id
month = int(days/30)
max_temp_month = max_temp[month]
min_temp_month = min_temp[month]
# Use a Quadratic function with a vertex (min point) at 1st July 2020, with a temperature of -19.2
# Note that, from 1 Jan 2020 to 1 July 2020, there are 180 days, so b = 180, c = -19.2
# We calculate a such that, at x = 366, the value of the function is equal to the max temperature
# The max. temperature is at x = 0, with a temperature of 2.9
c = -19.2
b = 180
a = (2.9 - c)/(0 - b)**2
y = a*(days - b)**2 + c
return y
def antarctic_temp(hours):
"""
Calculates the temperature at one specific time of the day
:param hours: Hours since midnight on 1 Jan 2020
:return: Temperature
"""
# We know that the sine function varies between -1 and 1. So, if we declare a sine function
# with an amplitude of 3, we obtain a function that varies between -3 and 3, so this will be used for the
# fluctuations of the temperature around the mean
# Calculate at wich month does the given hours are for
days = int(hours/24) # Number of days
month = int(days/30) # number of month
max_temp_month = max_temp[month]
min_temp_month = min_temp[month]
# Calculate mean temperature for this month
mean_temp = (max_temp_month + min_temp_month)/2.0
# Calculate the hours for this specific day
day_hours = hours - days*24
mean_temp = average_antarctic_temp(days)
# The sine function must have a period of 24 hours. Then:
y = mean_temp + math.sin(2*math.pi/24.0 *day_hours)
return y
def heat_transfer(Tair):
"""
Calculate the anticipated heat transfer through penguin's coat according to model in Section 5.3
:param Tair: Temperature of air (ºC)
:return: Heat (Wm^-2)
"""
# Define the Stefan-Boltzman constant
sigma = 5.670E-8
# Define emissivity
epsilon = 0.8
# Convert the air temperature to kelvin
Tair_K = Tair + 273.15
# Define the temperature on the Sea surface T2
T2 = -0.8
# Convert to Kelvin
T2_K = T2 + 273.15
# Calculate heat transfer
qr = sigma*(Tair_K**4 - T2_K**4)/(24 + (2/epsilon - 1))
return qr
def getMonth():
"""
This function will ask to user for a month and will check if the input is valid. If the input
is now valid, the function will display an error message and reprompt the user
:return: month
"""
while True:
try:
month = input("Enter a month (1-12): ")
month = int(month)
if month >= 1 and month <= 12:
return month-1
else:
print("Please enter a valid month.")
except:
print("Please enter a valid month.")
def getInt(lb = 0):
"""
This function will ask to user for a positive inteher and will check if the input is valid. If the input
is now valid, the function will display an error message and reprompt the user
:param lb: Lower bound for the value entered by the user
:return: integer
"""
while True:
try:
n = input("Enter value: ")
n = int(n)
if n > lb:
return n
else:
print("Please enter a valid number.")
except:
print("Please enter a valid number.")
def askYesNo(message):
"""
This function will prompt the user to enter "yes" or "no". If the user enters an invalid answer, the function
will reprompt the user
:return: option entered by user as string in lower case
"""
while True:
option = input(message).lower()
if option in ["yes", "no"]:
return option
else:
print("Please enter a valid option.")
# Main program
if __name__ == '__main__':
# Print welcome message
print("Welcome!")
print('''
The Emperor Penguin (Aptenodytes forsteri) is the tallest and heaviest of all living penguin species and is endemic to Antarctica.\n
They usually live in seas with a temperature of -0.8 ºC and have a total of 14 humeral arterioes. The surface area for their wings is about 202 cm^2
''')
print('''
The antarctic temperatures are very low and for 2020, these temperatures varied between 2.9 ºC and -19.2 ºC
''')
while True:
month = getMonth()
# Convert the given month to hours since 1 Jan 2020
hours = month*24*30
# Calculate the temperatures over the month
temps = [antarctic_temp(i) for i in range(hours, hours+24*25)]
print(f"The daily average temperature (ºC) for month {month} are:")
print("{:<10s} {:>20s}".format("Day", "Temperature (ºC)"))
for i in range(30):
T = average_antarctic_temp((month-1)*30+i)
print("{:<10d} {:>20.2f}".format(i+1, T))
# Ask user if he/she is an "enthusiast"
option = askYesNo("Are you an enthusiast? (yes/no): ")
if option == "yes":
# Plot
plt.figure()
plt.plot(range(24*25), temps)
plt.grid(True)
plt.title(f"Temperature fluctuations for month {month+1}")
plt.xlabel('Hours')
plt.ylabel('Temperature (ºC)')
plt.show()
# Prompt for time of the day
print("Please enter a time of the day, in hours (1-24): ")
hour = getInt()
Tcalc = antarctic_temp((month-1)*30*24+hour)
print("The temperature (in ºC) at month {:.0f} at the hour {:.1f} is: {:.2f} ºC".format(month, hour, Tcalc))
# Display importance of feathers
print('''
The feathers in the Emperor Penguins are very important because they help to transfer the heat from the Penguin's body to the exterior
''')
print("Please enter the temperature of the air (in ºC): ")
Tair = getInt(-273.15)
# Calculate heat transfer
qr = heat_transfer(Tair)
print("The heat transfer between the Penguin's body and the exterior is: {0:.2f} Wm^-2".format(qr))
# Ask user if he/she wants to chose another month
option = askYesNo("Do you want to chose another month? (yes/no): ")
if option == "no":
break
print('''
Penguins keep their non-feathered extremities warm thanks to the humeral arteries and the surface area of their wings.
''')
option = askYesNo("Are you an enthusiast? (yes/no): ")
if option == "yes":
# Data of humeral arterioes vs wing surface area
arteries = [2, 3, 3, 3, 5, 8, 14]
area = [30, 68, 80, 82, 75, 159, 202]
sea_temp = [14.9, 11.6, 10.0, 8.7, -0.8, 3.3, -0.8]
# Fit
z = np.polyfit(arteries, area, 3)
p = np.poly1d(z)
y_fit = [p(i) for i in arteries]
plt.figure()
plt.scatter(arteries, area, label = "Data")
plt.plot(arteries, y_fit, label="Fit", color='red')
plt.xlabel('Number of Humeral Arteries')
plt.ylabel('Wing surface area (cm^2)')
plt.grid(True)
plt.legend()
plt.title("Wing Surface Area vs. Number of Humeral Arteries")
plt.show()
# Now fit model for sea temp
z2 = np.polyfit(arteries, sea_temp, 3)
p2 = np.poly1d(z2)
y_fit2 = [p2(i) for i in arteries]
plt.figure()
plt.scatter(arteries, sea_temp, label="Data")
plt.plot(arteries, y_fit2, label="Fit", color='red')
plt.xlabel('Number of Humeral Arteries')
plt.ylabel('Temperature at surface of the Sea (ºC)')
plt.grid(True)
plt.legend()
plt.title("Sea Tempterature vs. Number of Humeral Arteries")
plt.show()
print("Good Bye!")