Extend the exercise from today by applying what you've just learned about packages and code reusability.
import
to access these functions from another file or a notebookSince this is the solution, we are skipping the step of creating a separate script
In [1]:
def calc_heat_flux(u_atm, t_sea, rho=1.2, c_p=1004.5, c_h=1.2e-3, u_sea=1, t_atm=17):
q = rho * c_p * c_h * (u_atm - u_sea) * (t_sea - t_atm)
return q
2. Create yet another function that takes the name of the region as an input and returns SST values for the corresponding region
region_name
by experiment_name
or whatever you prefer
In [2]:
def create_sst(region_name):
"""
Create fake SST data (degC) for a given region
Inputs
------
region_name: ...continue the docstring...
n: integer, optional. Length of the returned data list
Returns
-------
...continue the docstring...
"""
if region_name == 'NS':
# North Sea
sst = list(range(5, 15, 1))
elif region_name == 'WS':
# White Sea
sst = list(range(0, 10, 1))
elif region_name == 'BS':
# Black Sea
sst = list(range(15, 25, 1))
else:
raise ValueError('Input value of {} is not recognised'.format(region_name))
return sst
4. Create the wind speed data
In [3]:
wind_speed = list(range(0,20,2))
5. Create a dictionary of data, whose keys are names of regions and values are lists of heat fluxes data
hf_dict
or whatever sounds better to youcreate_sst()
function and assign it to a variable, e.g. fake_sst
hf_dict
In [4]:
regions = ['WS', 'BS']
hf_dict = dict()
for reg in regions:
fake_sst = create_sst(reg)
heat_flux = []
for u, t in zip(wind_speed, fake_sst):
q = calc_heat_flux(u, t)
heat_flux.append(q)
hf_dict[reg] = heat_flux
Print the result to test yourself.
In [5]:
hf_dict
Out[5]:
6. Save the dictionary to text file, both keys and values
hf_dict
's keys as row (column) names
In [6]:
with open('heat_flux_var_sst_bycol.txt', 'w') as f:
column_names = sorted(hf_dict.keys())
f.write(','.join(column_names)+'\n')
for tup in zip(*[hf_dict[i] for i in column_names]):
f.write(','.join([str(i) for i in tup])+'\n')
In [7]:
with open('heat_flux_var_sst_byrow.txt', 'w') as f:
for k, v in hf_dict.items():
line = k + ','
for i in v:
line += str(i) + ','
line = line[:-1]+ '\n'
f.write(line)
In [8]:
!more {f.name}
Bonus
In [9]:
import json
Explore what json.dump() does.