Solution: create a module and reuse code from it (1 h)

Extend the exercise from today by applying what you've just learned about packages and code reusability.

Outline

  1. Put the function into a separate .py file
  2. Create yet another function that takes the name of the region as an input and returns SST values for the corresponding region
  3. Use import to access these functions from another file or a notebook
  4. Create the wind speed data
  5. Create a dictionary of data, whose keys are names of regions and values are lists of heat fluxes data
  6. Save the dictionary to text file (bonus: to a json file), both keys and values

Since 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

  • This function can look something like the one below
  • Feel free to modify or extend it
  • You can replace region_name by experiment_name or whatever you prefer
  • For convenience, make sure the length of the returned list is the same

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

  • Create a list of names of the regions/experiments
  • Create an empty dictionary, named hf_dict or whatever sounds better to you
  • Loop over the names, call the create_sst() function and assign it to a variable, e.g. fake_sst
  • Still inside the name-loop, write another loop to iterate over SST and wind values, just as you did in the previous exercise, and calculate the heat flux.
  • Assign the result to the corresponding key of 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]:
{'BS': [2.8929599999999995,
  -1.4464799999999998,
  0.0,
  7.232399999999998,
  20.250719999999998,
  39.054959999999994,
  63.64511999999999,
  94.02119999999998,
  130.18319999999997,
  172.13111999999998],
 'WS': [24.590159999999997,
  -23.143679999999996,
  -65.0916,
  -101.25359999999998,
  -131.62967999999998,
  -156.21983999999998,
  -175.02407999999997,
  -188.04239999999996,
  -195.27479999999997,
  -196.72127999999998]}

6. Save the dictionary to text file, both keys and values

  • You can copy the code for writing data to a text file from the previous exercise
  • Modify it so that the output file would include 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}


BS,2.8929599999999995,-1.4464799999999998,0.0,7.232399999999998,20.2507199999999
98,39.054959999999994,63.64511999999999,94.02119999999998,130.18319999999997,172
.13111999999998
WS,24.590159999999997,-23.143679999999996,-65.0916,-101.25359999999998,-131.6296
7999999998,-156.21983999999998,-175.02407999999997,-188.04239999999996,-195.2747
9999999997,-196.72127999999998

Bonus


In [9]:
import json

Explore what json.dump() does.