# MORDM VIII: Characterizing the effects of deep uncertainty

In the previous post, we defined robustness using the satisficing metric where (1) reliability should be at least 98%, (2) restriction frequency should be not more than 10% and (3) worst-case cost of drought mitigation action should not be more than 10% of annual net volumetric income. To calculate the robustness of these set of actions (portfolios) against the effects of challenging states of the world (SOWs) on the initial set of actions, we once again re-simulated them to discover how they fail.

In this penultimate post, we will perform simple sensitivity analysis across the average performance of all sixty-nine portfolios of actions to understand which uncertainties control the performance of each utility (Raleigh, Durham and Cary) and the regions across all uncertain SOWs.

### Calculating average performance across 100 DU SOWs

First, we create a new folder to hold the output of the next few post-processing steps. Navigate to the WaterPaths/ folder and create a folder called post_processing. Now, let’s calculate the average performance of each of the sixty-nine initial portfolios across the 100 DU SOWs that we previously simulated them over. The code for this can be found in the post_processing_code folder under gather_objs.py file and should look like this:

# -*- coding: utf-8 -*-
"""
Created on Mon April 26 2022 11:12

@author: Lillian Bei Jia Lau
Organizes output objectives by mean across RDMs and across solutions

"""
import numpy as np

obj_names = ['REL_C', 'RF_C', 'INF_NPC_C', 'PFC_C', 'WCC_C', \
'REL_D', 'RF_D', 'INF_NPC_D', 'PFC_D', 'WCC_D', \
'REL_R', 'RF_R', 'INF_NPC_R', 'PFC_R', 'WCC_R', \
'REL_reg', 'RF_reg', 'INF_NPC_reg', 'PFC_reg', 'WCC_reg']

'''
Performs regional minimax
'''
def minimax(N_SOLNS, objs):
for i in range(N_SOLNS):
for j in range(5):
if j == 0:
objs[i,15] = np.min([objs[i,0],objs[i,5], objs[i,10]])
else:
objs[i, (j+15)] = np.max([objs[i,j],objs[i,j+5], objs[i,j+10]])
return objs

'''
Calculates the mean performance acorss all SOWs
'''
def mean_performance_across_rdms(objs_by_rdm_dir, N_RDMS, N_SOLNS):
objs_matrix = np.zeros((N_SOLNS,20,N_RDMS), dtype='float')
objs_means = np.zeros((N_SOLNS,20), dtype='float')

for i in range(N_RDMS):
filepathname = objs_by_rdm_dir + str(i) + '_sols0_to_' + str(N_SOLNS) + '.csv'
objs_matrix[:,:15,i] = objs_file

objs_file_wRegional = minimax(N_SOLNS, objs_matrix[:,:,i])

objs_matrix[:,:,i] = objs_file_wRegional

array_has_nan = np.isnan(np.mean(objs_matrix[:,3,i]))
if(array_has_nan == True):
print('NaN found at RDM ', str(i))

for n in range(N_SOLNS):
for n_objs in range(20):
objs_means[n,n_objs] = np.mean(objs_matrix[n,n_objs,:])

return objs_means

'''
Calculates the mean performance acorss all SOWs
'''
def mean_performance_across_solns(objs_by_rdm_dir, N_RDMS, N_SOLNS):
objs_matrix = np.zeros((N_SOLNS,20,N_RDMS), dtype='float')
objs_means = np.zeros((N_RDMS,20), dtype='float')

for i in range(N_RDMS):
filepathname = objs_by_rdm_dir + str(i) + '_sols0_to_' + str(N_SOLNS) + '.csv'
objs_matrix[:,:15,i] = objs_file
objs_file_wRegional = minimax(N_SOLNS, objs_matrix[:,:,i])

objs_matrix[:,:,i] = objs_file_wRegional

array_has_nan = np.isnan(np.mean(objs_matrix[:,3,i]))
if(array_has_nan == True):
print('NaN found at RDM ', str(i))

for n in range(N_RDMS):
for n_objs in range(20):
objs_means[n,n_objs] = np.mean(objs_matrix[:,n_objs,n])

return objs_means

# change number of solutions available depending on the number of solutions
# that you identified
N_SOLNS = 69
N_RDMS = 100

# change the filepaths
objs_by_rdm_dir = '/yourFilePath/WaterPaths/output/Objectives_RDM'
objs_og_dir = '/yourFilePath/WaterPaths/'

fileoutpath = '/yourFilePath/WaterPaths/post_processing/'

fileoutpath_byRDMs = fileoutpath + 'meanObjs_acrossRDM.csv'
fileoutpath_bySoln = fileoutpath + 'meanObjs_acrossSoln.csv'

# should have shape (N_SOLNS, 20)
objs_byRDM = mean_performance_across_rdms(objs_by_rdm_dir, N_RDMS, N_SOLNS)
# should have shape (N_RDMS, 20)
objs_bySoln = mean_performance_across_solns(objs_by_rdm_dir, N_RDMS, N_SOLNS)

np.savetxt(fileoutpath_byRDMs, objs_byRDM, delimiter=",")
np.savetxt(fileoutpath_bySoln, objs_bySoln, delimiter=",")

This will output two .csv files: meanObjs_acrossRDM.csv contains the average performance of each of the sixty-nine objectives evaluated over 100 DU SOWs, while meanObjs_acrossSoln.csv contains the average performance of all solutions within one SOW. Take some time to understand this difference, as this will be important when performing sensitivity analysis and scenario discovery.

### Calculate the robustness of each portfolio to deep uncertainty

Now, let’s identify how each of these solutions perform under a set of more challenging SOWs. Within post_processing_code/, identify the file called calc_robustness_across_rdms.py. It should look like this:

# -*- coding: utf-8 -*-
"""
Created on Mon April 26 2022 11:12

@author: Lillian Bei Jia Lau

Calculates the fraction of RDMs over which each perturbed version of the solution meets all four satisficing criteria
"""
import numpy as np
import pandas as pd

obj_names = ['REL_C', 'RF_C', 'INF_NPC_C', 'PFC_C', 'WCC_C', \
'REL_D', 'RF_D', 'INF_NPC_D', 'PFC_D', 'WCC_D', \
'REL_R', 'RF_R', 'INF_NPC_R', 'PFC_R', 'WCC_R', \
'REL_reg', 'RF_reg', 'INF_NPC_reg', 'PFC_reg', 'WCC_reg']

utilities = ['Cary', 'Durham', 'Raleigh', 'Regional']

'''
Performs regional minimax
'''
def minimax(N_SOLNS, objs):
for i in range(N_SOLNS):
for j in range(5):
if j == 0:
objs[i,15] = np.min([objs[i,0],objs[i,5], objs[i,10]])
else:
objs[i, (j+15)] = np.max([objs[i,j],objs[i,j+5], objs[i,j+10]])
return objs

'''
For each rdm, identify if the perturbed solution version x satisfies the satisficing criteria
'''
def satisficing(df_objs):
for i in range(4):
df_objs['satisficing_C'] = (df_objs['REL_C'] >= 0.98).astype(int) *\
(df_objs['WCC_C'] <= 0.10).astype(int) *\
(df_objs['RF_C'] <= 0.10).astype(int)

df_objs['satisficing_D'] = (df_objs['REL_D'] >= 0.98).astype(int) *\
(df_objs['WCC_D'] <= 0.10).astype(int) *\
(df_objs['RF_D'] <= 0.10).astype(int)

df_objs['satisficing_R'] = (df_objs['REL_R'] >= 0.98).astype(int) *\
(df_objs['WCC_R'] <= 0.10).astype(int) *\
(df_objs['RF_R'] <= 0.10).astype(int)

df_objs['satisficing_reg'] = np.max(df_objs.iloc[:, 20:23])
return df_objs

def calc_robustness(objs_by_rdm_dir, N_RDMS, N_SOLNS):

# matrix structure: (N_SOLNS, N_OBJS, N_RDMS)
objs_matrix = np.zeros((N_SOLNS,20,N_RDMS), dtype='float')

satisficing_matrix = np.zeros((N_SOLNS,4,N_RDMS), dtype='float')
solution_robustness = np.zeros((N_SOLNS,4), dtype='float')

for i in range(N_RDMS):
# get one perturbed instance's behavior over all RDMs
filepathname = objs_by_rdm_dir + str(i) + '_sols0_to_' + str(N_SOLNS) + '.csv'

objs_matrix[:,:15,i] = objs_file

objs_file_wRegional = minimax(N_SOLNS, objs_matrix[:,:,i])

objs_matrix[:,:,i] = objs_file_wRegional

# NaN check
array_has_nan = np.isnan(np.mean(objs_matrix[:,3,i]))
if(array_has_nan == True):
print('NaN found at RDM ', str(i))

# for the perturbed instances
for r in range(N_RDMS):

df_curr_rdm = pd.DataFrame(objs_matrix[:, :, r], columns = obj_names)

df_curr_rdm = satisficing(df_curr_rdm)
satisficing_matrix[:N_SOLNS,:,r] = df_curr_rdm.iloc[:,20:24]

for n in range(N_SOLNS):
solution_robustness[n,0] = np.sum(satisficing_matrix[n,0,:])/N_RDMS
solution_robustness[n,1] = np.sum(satisficing_matrix[n,1,:])/N_RDMS
solution_robustness[n,2] = np.sum(satisficing_matrix[n,2,:])/N_RDMS

solution_robustness[:,3] = np.min(solution_robustness[:,:3], axis=1)

return solution_robustness

'''
Change number of solutions available depending on the number of solutions
that you identified and the number of SOWs that you are evaluating them over.
'''
N_RDMS = 100
N_SOLNS = 69

objs_by_rdm_dir = '/scratch/lbl59/blog/WaterPaths/output/Objectives_RDM'

fileoutpath_robustness = '/scratch/lbl59/blog/WaterPaths/post_processing/' + \
'robustness_' + str(N_RDMS) + '_SOWs.csv'

robustness = calc_robustness(objs_by_rdm_dir, N_RDMS, N_SOLNS)

np.savetxt(fileoutpath_robustness, robustness, delimiter=",")

When you run this script from the terminal, you should have a .csv file called ‘robustness_100_SOWs.csv‘ appear in your post_processing/ folder. Now, let’s get onto some sensitivity analysis!

### Delta moment-independent sensitivity analysis

The Delta moment-independent (DMI) method (Borgonovo, 2007) is sensitivity analysis method that compares the entire probability distribution of both input and output parameters to estimate the sensitivity of the output to a specific input parameter. It is one of many global sensitivity analysis methods, which in itself is one of two main categories of sensitivity analysis that enables the assessment of the degree to which uncertainty in model inputs map to the degree of uncertainty in model output. For purposes of this test case, the DMI is preferable as it does not rely on any one statistical moment (variance, mean and skew) to describe the dependence of model output to its input parameters. It is also time-sensitive, reflecting the current state of knowledge within the system, which philosophically pairs well with our use of the ROF triggers. More information on alternative global sensitivity methods can be found here.

Within the context of our test case, we will be using the DMI method to identify uncertainties in our decision variables that most strongly influence our performance over the 100 DU SOWs. To perform DMI sensitivity analysis, first navigate to the post_processing/ folder. Within the folder, create two sub-folders called delta_output_DV/ and delta_output_DUF/. This is where all your DMI output will be stored. Next, locate the delta_sensitivity.py file within the post_processing_code/ folder. The code should look similar to the script provided below:

import sys
from SALib.analyze import delta
import numpy as np
import pandas as pd

'''
Finds the upper and lower bounds of input parameters
'''
def find_bounds(input_file):
bounds = np.zeros((input_file.shape[1],2), dtype=float)
for i in range(input_file.shape[1]):
bounds[i,0] = min(input_file[:,i])
bounds[i,1] = max(input_file[:,i])

return bounds
'''
Performs delta moment-independent sensitivity analysis
Source: https://github.com/SALib/SALib/tree/main/examples/delta
'''
def delta_sensitivity(dec_vars, measured_outcomes, names, mo_names, bounds, rdm, mode):
X = dec_vars
Y = measured_outcomes

problem = {
'num_vars': int(dec_vars.shape[1]),
'names': names,
'bounds': bounds
}

for i in range(measured_outcomes.shape[1]):
mo_label = mo_names[i]
if i == 2 and mode == 'objs':
break
else:
filename = '../post_processing/delta_output_' + rdm + '/S1_' + mo_label + '.csv'
S1 = delta.analyze(problem, X, Y[mo_label].values, num_resamples=10, conf_level=0.95, print_to_console=False)
numpy_S1 = np.array(S1["S1"])
fileout = pd.DataFrame([names, numpy_S1], index = None, columns = None)
fileout.to_csv(filename, sep=",")

'''
0 - Name all file headers and compSol to be analyzed
'''
obj_names = ['REL_C', 'RF_C', 'INF_NPC_C', 'PFC_C', 'WCC_C', \
'REL_D', 'RF_D', 'INF_NPC_D', 'PFC_D', 'WCC_D', \
'REL_R', 'RF_R', 'INF_NPC_R', 'PFC_R', 'WCC_R', \
'REL_reg', 'RF_reg', 'INF_NPC_reg', 'PFC_reg', 'WCC_reg']

dv_names = ['RT_C', 'RT_D', 'RT_R', 'TT_D', 'TT_R', 'LMA_C', 'LMA_D', 'LMA_R',\
'RC_C', 'RC_D', 'RC_R', 'IT_C', 'IT_D', 'IT_R', 'IP_C', 'IP_D', \
'IP_R', 'INF_C', 'INF_D', 'INF_R']

rdm_headers_dmp = ['Cary restr. eff', 'Durham restr. eff', 'Raleigh restr. eff']
rdm_headers_utilities = ['Demand growth\nmultiplier', 'Bond term\nmultiplier', \
'Bond interest\nrate multiplier', 'Infrastructure interest\nrate multiplier']
rdm_headers_ws = ['Streamflow amp', 'SCR PT', 'SCR CT', 'NRR PT', 'NRR CT', 'CR Low PT', 'CR Low CT',\
'CR High PT', 'CR High CT', 'WR1 PT', 'WR1 CT', 'WR2 PT', 'WR2 CT',\
'DR PT', 'DR CT', 'FR PT', 'FR CT']

duf_names = ['Cary restr. eff', 'Durham restr. eff', 'Raleigh restr. eff', 'Demand growth\nmultiplier',\
'Bond term\nmultiplier', 'Bond interest\nrate multiplier', 'Infrastructure interest\nrate multiplier',\
'Streamflow amp\nmultiplier', 'SCR PT\nmultiplier', 'SCR CT\nmultiplier', 'NRR PT\nmultiplier',\
'NRR CT\nmultiplier', 'CR Low PT\nmultiplier', 'CR Low CT\nmultiplier', 'CR High PT\nmultiplier',\
'CR High CT\nmultiplier', 'WR1 PT\nmultiplier', 'WR1 CT\nmultiplier', 'WR2 PT\nmultiplier',\
'WR2 CT\nmultiplier', 'DR PT\nmultiplier', 'DR CT\nmultiplier', 'FR PT\nmultiplier', 'FR CT\nmultiplier',\
'DR PT\nmultiplier', 'DR CT\nmultiplier', 'FR PT\nmultiplier', 'FR CT\nmultiplier']

utilities = ['Cary', 'Durham', 'Raleigh', 'Regional']

N_RDMS = 100
N_SOLNS = 69

'''
1 - Load DU factor files and DV files
'''
# change to your own filepath
rdm_factors_directory = '/yourFilePath/WaterPaths/TestFiles/'
rdm_dmp_filename = rdm_factors_directory + 'rdm_dmp_test_problem_reeval.csv'
rdm_utilities_filename = rdm_factors_directory + 'rdm_utilities_test_problem_reeval.csv'
rdm_watersources_filename = rdm_factors_directory + 'rdm_water_sources_test_problem_reeval.csv'

dufs = pd.concat([rdm_dmp, rdm_utilities, rdm_ws], axis=1, ignore_index=True)
duf_numpy = dufs.to_numpy()

# change to your own filepath
dv_directory = '/yourFilePath/WaterPaths/'

'''
2 - Get bounds for DU factors and DVs
'''
duf_bounds = find_bounds(duf_numpy)
dv_bounds = find_bounds(dvs)

'''
3 - Load robustness file and objectives file
'''
# change to your own filepath
main_dir = '/yourFilePath/WaterPaths/post_processing/'

robustness_filename = main_dir + 'robustness_100_SOWs.csv'
robustness_df = pd.DataFrame(robustness_arr, columns=utilities)

objs_mean_rdm_filename = main_dir + 'meanObjs_acrossRDM.csv'
objs_mean_rdm_df = pd.DataFrame(objs_mean_rdm_arr, columns=obj_names)

objs_mean_soln_filename = main_dir + 'meanObjs_acrossSoln.csv'
objs_mean_soln_df = pd.DataFrame(objs_mean_soln_arr, columns=obj_names)

# to change  depending on whether DV or DUF is being analyzed
dec_vars = dvs
measured_outcomes = objs_mean_rdm_df
names = dv_names
mo_names = obj_names
bounds = dv_bounds
rdm = 'DV'
mode = 'objs'
###

delta_sensitivity(dec_vars, measured_outcomes, names, mo_names, bounds, rdm, mode)

The code above identifies the sensitivity of the average values of all sixty-nine performance objective sets over all 100 deeply-uncertain SOWs to the decision variables. This is why we use the meanObjs_acrossRDM.csv file – this file contains sixty-nine mean values of the performance objectives, where each set of performance objectives inversely maps to their corresponding portfolio of actions.

To identify the sensitivity of performance objectives to the DU factors, change lines 121 to 127 to the following:

# to change  depending on whether DV or DUF is being analyzed
dec_vars = duf_numpy[:100,:]
measured_outcomes = objs_mean_soln_df
names = duf_names
mo_names = obj_names
bounds = duf_bounds[:100,:]
rdm = 'DUF'
mode = 'objs'
###

The code above identifies the sensitivity of the average values of all twenty performance objectives over each of the sixty-nine different portfolios to the set of deeply uncertain hydroclimatic and demand scenarios. This is why we use the meanObjs_acrossSoln.csv file – this file contains one hundred mean values of the performance objectives, where each set of performance objectives inversely maps to their corresponding DU SOW.

Great job so far! Now let’s visualize the sensitivity of our output to our input parameters using heatmaps. Before being able to visualize each utility’s performance sensitivity, we must first organize the sensitivity indices of the decision variables into a file containing the indices over all objectives for each utility. The gather_delta.py script does this. Simply change the value of mode on line 11 to ‘DUF‘ to gather the indices for the DU factors.

"""
Created on Tue April 26 2022 16:12

@author: Lillian Bei Jia Lau

Gathers the delta sensitivity indices into files per utility
"""
import numpy as np
import pandas as pd

mode = 'DV'
main_dir = '/yourFilePath/WaterPaths/post_processing/delta_output_' + mode + '/'
utilities = ['_C', '_D', '_R', '_reg']
objs = ['REL', 'RF', 'INF_NPC', 'PFC', 'WCC']
utilities_full = ['Cary', 'Durham', 'Raleigh', 'Regional']

dv_names = ['RT_C', 'RT_D', 'RT_R', 'TT_D', 'TT_R', 'LMA_C', 'LMA_D', 'LMA_R',\
'RC_C', 'RC_D', 'RC_R', 'IT_C', 'IT_D', 'IT_R', 'IP_C', 'IP_D', \
'IP_R', 'INF_C', 'INF_D', 'INF_R']

duf_names = ['Cary restr. eff', 'Durham restr. eff', 'Raleigh restr. eff', 'Demand growth\nmultiplier',\
'Bond term\nmultiplier', 'Bond interest\nrate multiplier', 'Infrastructure interest\nrate multiplier',\
'Streamflow amp\nmultiplier', 'SCR PT\nmultiplier', 'SCR CT\nmultiplier', 'NRR PT\nmultiplier',\
'NRR CT\nmultiplier', 'CR Low PT\nmultiplier', 'CR Low CT\nmultiplier', 'CR High PT\nmultiplier',\
'CR High CT\nmultiplier', 'WR1 PT\nmultiplier', 'WR1 CT\nmultiplier', 'WR2 PT\nmultiplier',\
'WR2 CT\nmultiplier', 'DR PT\nmultiplier', 'DR CT\nmultiplier', 'FR PT\nmultiplier', 'FR CT\nmultiplier',\
'DR PT\nmultiplier', 'DR CT\nmultiplier', 'FR PT\nmultiplier', 'FR CT\nmultiplier']

s1_dv_cary = np.zeros((len(objs), len(dv_names)), dtype=float)
s1_dv_durham = np.zeros((len(objs), len(dv_names)), dtype=float)
s1_dv_raleigh = np.zeros((len(objs), len(dv_names)), dtype=float)
s1_dv_regional = np.zeros((len(objs), len(dv_names)), dtype=float)

s1_dv_dict = {
'_C': s1_dv_cary,
'_D': s1_dv_durham,
'_R': s1_dv_raleigh,
'_reg': s1_dv_regional
}

s1_duf_cary = np.zeros((len(objs), len(duf_names)), dtype=float)
s1_duf_durham = np.zeros((len(objs), len(duf_names)), dtype=float)
s1_duf_raleigh = np.zeros((len(objs), len(duf_names)), dtype=float)
s1_duf_regional = np.zeros((len(objs), len(duf_names)), dtype=float)

s1_duf_dict = {
'_C': s1_duf_cary,
'_D': s1_duf_durham,
'_R': s1_duf_raleigh,
'_reg': s1_duf_regional
}

for i in range(len(utilities)):
s1_util = []
hdrs = []
if mode == 'DV':
s1_util = s1_dv_dict[utilities[i]]
hdrs = dv_names
elif mode == 'DUF':
s1_util = s1_duf_dict[utilities[i]]
hdrs = duf_names

for j in range(len(objs)):
curr_file = main_dir + 'S1_' + objs[j] + utilities[i] + '.csv'

s1_util_df = pd.DataFrame(s1_util, columns=hdrs)
out_filepath = main_dir + utilities_full[i] + '.csv'

s1_util_df.to_csv(out_filepath, sep=',', index=False)

Now, let’s plot our heatmaps! The code to do so can be found in sensitivity_heatmap.py, and should look similar to the code provided below:

import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import AxesGrid

sns.set_theme()

# change depending on compromise solution and whether its sensitivity to DUF or DVs
mode = 'DUF'
rot = 90    # if DV use 0; if DUF use 45
main_dir = '/YourFilePath/WaterPaths/post_processing/delta_output_' + mode + '/'
c_filepath = main_dir + 'Cary.csv'
d_filepath = main_dir + 'Durham.csv'
r_filepath = main_dir + 'Raleigh.csv'
reg_filepath = main_dir + 'Regional.csv'

savefig_dir = '/YourFilePath/WaterPaths/post_processing/'
savefig_name = savefig_dir + 'dmi_heatmap_' + mode + '.svg'

grid_kws = {"height_ratios": (0.20, 0.20, 0.20, 0.20, .02), "hspace": 0.5}
f, (ax1, ax2, ax3, ax4, cbar_ax) = plt.subplots(5, figsize=(15, 20), gridspec_kw=grid_kws)
plt.subplots_adjust(top = 0.95, bottom = 0.05,
hspace = 0, wspace = 0.05)

y_objs=['REL', 'RF', 'INPC', 'PFC', 'WCC']

x_dvs=['$RT_{C}$', '$RT_{D}$', '$RT_{R}$', '$TT_{D}$', '$TT_{R}$', '$LM_{C}$', '$LM_{D}$', '$LM_{R}$',\
'$RC_{C}$', '$RC_{D}$', '$RC_{R}$', '$IT_{C}$', '$IT_{D}$', '$IT_{R}$', '$IP_{C}$', \
'$IP_{D}$', '$IP_{R}$','$INF_{C}$', '$INF_{D}$', '$INF_{R}$']
x_dufs = ['Cary\nrestr. eff', 'Durham\nrestr. eff', 'Raleigh\nrestr. eff', 'Dem. growth\nmultiplier',\
'Bond term\nmultiplier', 'Bond interest\nrate multiplier', 'Infra. interest\nrate multiplier',\
'Streamflow amp\nmultiplier', 'SCR PT\nmultiplier', 'SCR CT\nmultiplier', 'NRR PT\nmultiplier',\
'NRR CT\nmultiplier', 'CR Low PT\nmultiplier', 'CR Low CT\nmultiplier', 'CR High PT\nmultiplier',\
'CR High CT\nmultiplier', 'WR1 PT\nmultiplier', 'WR1 CT\nmultiplier', 'WR2 PT\nmultiplier',\
'WR2 CT\nmultiplier', 'DR PT\nmultiplier', 'DR CT\nmultiplier', 'FR PT\nmultiplier', 'FR CT\nmultiplier',\
'DR PT\nmultiplier', 'DR CT\nmultiplier', 'FR PT\nmultiplier', 'FR CT\nmultiplier']

x_labs = []
if mode == 'DV':
x_labs = x_dvs
elif mode == 'DUF':
x_labs = x_dufs

plt.rc('xtick', labelsize=1)
plt.rc('ytick', labelsize=3)
plt.rc('axes', labelsize=5)
plt.rc('axes', titlesize=14)

ax1.set_title("Cary")
sns.heatmap(cary, linewidths=.05, cmap="YlOrBr", xticklabels=[],
yticklabels=y_objs, ax=ax1, cbar=False)
ax1.set_yticklabels(y_objs, rotation=0)

ax2.set_title("Durham")
sns.heatmap(durham, linewidths=.05, cmap="YlOrBr", xticklabels=[],
yticklabels=y_objs, ax=ax2, cbar=False)
ax2.set_yticklabels(y_objs, rotation=0)

ax3.set_title("Raleigh")
sns.heatmap(raleigh, linewidths=.05, cmap="YlOrBr", xticklabels=[],
yticklabels=y_objs, ax=ax3, cbar=False)
ax3.set_yticklabels(y_objs, rotation=0)

ax4.set_title("Regional")
ax4 = sns.heatmap(regional, linewidths=.05, cmap="YlOrBr", xticklabels=x_labs,
yticklabels=y_objs, ax=ax4, cbar=True, cbar_ax=cbar_ax,
cbar_kws={'orientation': 'horizontal'})     # change depending on whether analyzing DUF or DV
ax4.set_xticklabels(x_labs, rotation=rot, fontsize=10)
ax4.set_yticklabels(y_objs, rotation=0)

plt.savefig(savefig_name)

Running this for the sensitivity to decision variables and DU factors will generate the following images:

In the figure above, the color of each box represents the sensitivity of a performance objective (y-axis) to a specific decision variable (x-axis). It is interesting to note that the restriction triggers (RT) of all utilities strongly influence each of their individual and regional reliability and restriction frequency. This indicates the potential for regional conflict, as possible errors is operating one utility’s restriction trigger may adversely affect other utilities’ reliabilities and ability to maintain full control over their own use of water-use restrictions. Furthermore, Raleigh’s performance is sensitive to more decision variables than its remaining two counterparts, with it’s worst-case cost (WCC) being affected most by Cary’s infrastructure investments. This observation highlights the importance of careful cooperation between a region’s member utilities to ensure that all partners play their part in maintaining both their own and their counterparts’ performance.

In this next figure, we observe that uncertainty in demand growth is the only DU factor that significantly drives changes in individual and regional performance. This finding can thus help utilities to focus on demand management programs, or formulate operations and management policies that enable them to more quickly adapt to changes in consumer and industrial demand growth.

Overall, in this post, we have performed a simple sensitivity analysis to identify uncertainties in the decision variables and DU factors that control regional and individual performance. All the code for processing the output data can be found in this GitHub repository here. In the next post, we will end the MORDM blogpost series by performing scenario discovery to map regions of success and failure as defined by our robustness metrics.

## References

Borgonovo, E. (2007). A new uncertainty importance measure. Reliability Engineering &Amp; System Safety, 92(6), 771-784. doi: 10.1016/j.ress.2006.04.015

Herman, J. D., Reed, P. M., Zeff, H. B., & Characklis, G. W. (2015). How should robustness be defined for water systems planning under change? Journal of Water Resources Planning and Management, 141(10), 04015012. doi:10.1061/(asce)wr.1943-5452.0000509

Reed, P.M., Hadjimichael, A., Malek, K., Karimi, T., Vernon, C.R., Srikrishnan, V., Gupta, R.S., Gold, D.F., Lee, B., Keller, K., Thurber, T.B, & Rice, J.S. (2022). Addressing Uncertainty in Multisector Dynamics Research [Book]. Zenodo. https://doi.org/10.5281/zenodo.6110623

# Simple profiling checks for running jobs on clusters

The goal of this short blog post is to share some simple tips on profiling your (to be) submitted jobs on high performance computing resources. Profiling your jobs can give you information about how efficiently you are using your computational resources, i.e., your CPUs and your allocated memory. Typically you would perform these checks on your experiment at a smaller scale, ensuring that everything is working as it should, before expanding to more tasks and CPUs.

Your first check is squeue typically paired with your user ID on a cluster. Here’s an example:

(base) [ah986@login02 project_dir]$squeue -u ah986 JOBID PARTITION NAME USER ST TIME NODES NODELIST(REASON) 5688212 shared <job_name> ah986 R 0:05 1 exp-4-55 This tells me that my submitted job is utilizing 1 node in the shared partition of this cluster. If your cluster is using the SLURM scheduler, you can also use sacct which can display accounting data for all jobs you are currently running or have run in the past. There’s many pieces of information available with sacct, that you can specify using the --format flag. Here’s an example for the same job: (base) [ah986@login02 project_dir]$ sacct --format=JobID,partition,state,time,start,end,elapsed,nnodes,ncpus,nodelist,AllocTRES%32 -j 5688212
JobID  Partition      State  Timelimit               Start                 End    Elapsed   NNodes      NCPUS        NodeList                        AllocTRES
------------ ---------- ---------- ---------- ------------------- ------------------- ---------- -------- ---------- --------------- --------------------------------
5688212          shared    RUNNING   20:00:00 2021-09-08T10:55:40             Unknown   00:19:47        1        100        exp-4-55 billing=360000,cpu=100,mem=200G+
5688212.bat+               RUNNING            2021-09-08T10:55:40             Unknown   00:19:47        1        100        exp-4-55          cpu=100,mem=200G,node=1
5688212.0                  RUNNING            2021-09-08T10:55:40             Unknown   00:19:47        1        100        exp-4-55          cpu=100,mem=200G,node=1

In this case I can see the number of nodes (1) and the number of cores (100) utilized by my job as well as the resources allocated to it (100 CPUs and 200G of memory on 1 node). This information is useful in cases where a task launches other tasks and you’d like to diagnose whether the correct number of cores is being used.

Another useful tool is seff, which is actually a wrapper around sacct and summarizes your job’s overall performance. It is a little unreliable while the job is still running, but after the job is finished you can run:

(base) [ah986@login02 project_dir]$seff 5688212 Job ID: 5688212 Cluster: expanse User/Group: ah986/pen110 State: COMPLETED (exit code 0) Nodes: 1 Cores per node: 100 CPU Utilized: 1-01:59:46 CPU Efficiency: 68.16% of 1-14:08:20 core-walltime Job Wall-clock time: 00:22:53 Memory Utilized: 38.25 GB Memory Efficiency: 19.13% of 200.00 GB The information here is very useful if you want to find out about how efficiently you’re using your resources. For this example I had 100 separate tasks I needed to perform and I requested 100 cores on 1 node and 200 GB of memory. These results tell me that my job completed in 23mins or so, the total time using the CPUs (CPU Utilized) was 01:59:46, and most importantly, the efficiency of my CPU use. CPU Efficiency is calculated “as the ratio of the actual core time from all cores divided by the number of cores requested divided by the run time”, in this case 68.16%. What this means it that I could be utilizing my cores more efficiently by allocating fewer cores to the same number of tasks, especially if scaling up to a larger number of nodes/cores. Additionally, my allocated memory is underutilized and I could be requesting a smaller memory allocation without inhibiting my runs. Finally, while your job is still running you can log in the node(s) executing the job to look at live data. To do so, you simply ssh to one of the nodes listed under NODELIST (not all clusters allow this). From there, you can run the top command like below (with your own username), which will start the live task manager: (base) [ah986@r143 ~]$ top -u ah986

top - 15:17:34 up 25 days, 19:55,  1 user,  load average: 0.09, 12.62, 40.64
Tasks: 1727 total,   2 running, 1725 sleeping,   0 stopped,   0 zombie
%Cpu(s):  0.3 us,  0.1 sy,  0.0 ni, 99.6 id,  0.0 wa,  0.0 hi,  0.0 si,  0.0 st
MiB Mem : 257662.9 total, 249783.4 free,   5561.6 used,   2317.9 buff/cache
MiB Swap: 716287.0 total, 716005.8 free,    281.2 used. 250321.1 avail Mem

PID USER      PR  NI    VIRT    RES    SHR S  %CPU  %MEM     TIME+ COMMAND
78985 ah986     20   0  276212   7068   4320 R   0.3   0.0   0:00.62 top
78229 ah986     20   0  222624   3352   2936 S   0.0   0.0   0:00.00 slurm_script
78467 ah986     20   0  259464   8128   4712 S   0.0   0.0   0:00.00 srun
78468 ah986     20   0   54520    836      0 S   0.0   0.0   0:00.00 srun
78481 ah986     20   0  266404  19112   4704 S   0.0   0.0   0:00.24 parallel
78592 ah986     20   0  217052    792    720 S   0.0   0.0   0:00.00 sleep
78593 ah986     20   0  217052    732    660 S   0.0   0.0   0:00.00 sleep
78594 ah986     20   0  217052    764    692 S   0.0   0.0   0:00.00 sleep
78595 ah986     20   0  217052    708    636 S   0.0   0.0   0:00.00 sleep
78596 ah986     20   0  217052    708    636 S   0.0   0.0   0:00.00 sleep
78597 ah986     20   0  217052    796    728 S   0.0   0.0   0:00.00 sleep
78598 ah986     20   0  217052    732    660 S   0.0   0.0   0:00.00 sleep

Memory and CPU usage can be tracked from RES and %CPU columns respectively. In this case, for the sake of an example, I just assigned all my cores to sleep a certain number of minutes each (using no CPU or memory). Similar information can also be obtained using the ps command, with memory being tracked under the RSS column.

(base) [ah986@r143 ~]$ps -u$USER -o %cpu,rss,args
0.0  3352 /bin/bash /var/spool/slurm/d/job3509431/slurm_script
0.0  8128 srun --export=all --exclusive -N1 -n1 parallel -j 100 sleep {}m ::: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
0.0   836 srun --export=all --exclusive -N1 -n1 parallel -j 100 sleep {}m ::: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
0.1 19112 /usr/bin/perl /usr/bin/parallel -j 100 sleep {}m ::: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
0.0   792 sleep 3m
0.0   732 sleep 4m
0.0   764 sleep 5m
0.0   708 sleep 6m
0.0   708 sleep 7m
0.0   796 sleep 8m
0.0   732 sleep 9m
0.0   712 sleep 10m

# Basics of data visualization with ggplot2

In my previous post, I showed how wonderful the ggplot2 library in R is for visualizing complex networks. I realized that while there are several posts on this blog going over the advanced visualization capabilities of the ggplot2 library, there isn’t a primer on structuring code for creating graphs in R…yet. In this post, I will go over the syntax for creating pretty ggplot2 graphs and tweaking various parameters. I am a self-declared Python aficionado, but love using ggplot2 because it is intuitive to use, beginner-friendly, and highly customizable all at the same time.

## Dataset and setup

For this tutorial, I will be using one of the built-in datasets in R called mtcars which was extracted from the 1974 Motor Trend US magazine, and comprises fuel consumption and 10 aspects of automobile design and performance for 32 automobiles. Further documentation on this dataset can be found here. We import the data into our RStudio workspace.

# import the library into our workspace
library(ggplot2)

# import dataset
data(mtcars)

The resultant dataset looks something like this.

## Basic plot

Now that we have the data, we can get to plotting with ggplot2. We can declaratively create graphics using this library. We just have to provide the data, specify how to map properties to graph aesthetics, and the library takes care of the rest for us! We need to specify three things for each ggplot — 1) the data, 2) the aesthetics, and 3) the geometry.

Let us start by creating a basic scatterplot of the mileage (mpg) of each car as a function of its horsepower (hp). In this case the data is our dataframe mtcars, and the aesthetics x and y will be defined as the names of the columns we wish to plot along each axis — hp and mpg. We can also set the color aesthetic to indicate the number of cylinders (cyl) in each car. One of the reasons ggplot2 is so user-friendly is because each graph property can be tacked on to the same line of code with a + sign. Since we want a scatterplot, the geometry will be defined using geom_point().

# basic scatterplot
g <- ggplot(data = mtcars, aes(x = hp, y = mpg, color=cyl))
g + geom_point()

Excellent! The library automatically assigns the column names as axis labels, and uses the default theme and colors, but all of this can be modified to suit our tastes and to create pretty graphs. It is also important to note that we could have visualized the same data (less helpfully) as a line plot instead of a scatterplot, just by tweaking the geometry function.

# basic line plot
g + geom_line()

Well, this looks unpleasant. But wait, we can do so much more. We can also layer multiple geometries on the same graph to make more interesting plots.

# basic scatter+line plot
g + geom_line() + geom_point()

Additionally, we can tweak the geometry properties in each graph. Here is how we can transform the lines to dotted, and specify line widths and marker shape and size.

# change properties of geometry
g + geom_point(shape = "diamond", size = 3) +
geom_line(color = "black", linetype = "dotted", size = .3)

While our graph looks much neater now, using a line plot is actually pretty unhelpful for our dataset since each data point is a separate car. We will stick with a scatterplot for the rest of this tutorial. However, the above sort of graph would work great for time series data or other data that measures change in one variable.

## Axis labels

One of the cardinal rules of good data visualization is to add axis labels to your graphs. While R automatically set the axis labels to be column headers, we can override this to make the axis labels more informative with just one extra function.

# change axis titles
g + geom_point(shape = "diamond", size = 3) +
labs(x = "Horsepower (hp)", y = "Mileage (mpg)")

## Title

This graph is in serious need of a title to provide a reader some idea of what they’re looking at. There are actually multiple ways to add a graph title here, but I find it easiest to use ggtitle().

g + geom_point(shape = "diamond", size = 3) +
labs(x = "Horsepower (hp)", y = "Mileage (mpg)") +
ggtitle("Mileage vs Horsepower")

Alright, having a title is helpful, but I don’t love it’s placement on the graph. R automatically left-aligns the title, where it clashes with the y-axis. I would much rather have the title right-aligned, in a bigger font, and bolded. Here is how to do that.

# change position of title
g + geom_point(shape = "diamond", size = 3) +
labs(x = "Horsepower (hp)", y = "Mileage (mpg)") +
ggtitle("Mileage vs Horsepower")  +
theme(plot.title = element_text(hjust = 1, size = 15, face = "bold"))

## Theme

There are ways to manually change the background and gridlines of ggplot2 graphs using theme(), but an easy workaround is to use the built-in themes. Which theme you use depends greatly on the graph type and formatting guidelines, but I personally like a white background, faint gridlines, and a bounding box. One thing to note here though is that theme_bw() overrides theme() so the order of these two matters.

g + geom_point(shape = "diamond", size = 3) +
labs(x = "Horsepower (hp)", y = "Mileage (mpg)") +
ggtitle("Mileage vs Horsepower") +
theme_bw() +
theme(plot.title = element_text(hjust = 1, size = 15, face = "bold"))

We can also use the theme() function to change the base font size and font family. Shown below is how to increase the base font size to 15 and change the base font family to Courier.

# use theme to change base font family and font size
g + geom_point(shape = "diamond", size = 3) +
labs(x = "Horsepower (hp)", y = "Mileage (mpg)") +
ggtitle("Mileage vs Horsepower")  +
theme_bw(base_size = 15, base_family = "Courier") +
theme(plot.title = element_text(hjust = 1, size = 15, face = "bold"))

## Legend

It has been bothering me for the last seven paragraphs that my legend title still uses the column name. However, this is an easy fix. All I have to do is add a label to the color aesthetic in the labs() function.

# change legend title
g + geom_point(shape = "diamond", size = 3) +
labs(x = "Horsepower (hp)", y = "Mileage (mpg)", color = "Cylinders") +
ggtitle("Mileage vs Horsepower") +
theme_bw() +
theme(plot.title = element_text(hjust = 1, size = 15, face = "bold"))

We can also change the position of the legend. R automatically places legends on the right, and while I like having it to the right in this case, I could also place the legend at the bottom of the graph. This automatically changes the aspect ratio of the graph.

# change legend position
g + geom_point(shape = "diamond", size = 3) +
labs(x = "Horsepower (hp)", y = "Mileage (mpg)", color = "Cylinders") +
ggtitle("Mileage vs Horsepower") +
theme_bw() +
theme(plot.title = element_text(hjust = 1, size = 15, face = "bold")) +
theme(legend.position = "bottom")

## Margins

The theme() function is of endless use in ggplot2, and can be used to manually adjust the graph margins and add/remove white space padding. The order of arguments in margin() is counterclockwise — top, right, bottom, left (helpfully remembered by the pneumonic TRouBLe).

g + geom_point(shape = "diamond", size = 3) +
labs(x = "Horsepower (hp)", y = "Mileage (mpg)", color = "Cylinders") +
ggtitle("Mileage vs Horsepower") +
theme_bw() +
theme(plot.title = element_text(hjust = 1, size = 15, face = "bold")) +
theme(legend.position = "right") +
theme(plot.margin = margin(t = 1, r = 1, b = 1, l = 2, unit = "cm"))

## Conclusion

I have barely scratched the surface of what can be achieved using ggplot2 in this post. There are hundreds of excellent tutorials online that dive deeper into ggplot2, like this blog post by Cedric Scherer. I have yet to learn so much about this library and data visualization in general, but have hopefully made a solid case for using ggplot2 to create clean and aesthetically-pleasing data visualizations.

# Job scheduling on HPC resources

## Architecture of a HPC Cluster

Modern High Performance Computing (HPC) resources are usually composed of a cluster of computing nodes that provide the user the ability to parallelize tasks and greatly reduce the time it takes to perform complex operations. A node is usually defined as a discrete unit of a computer system that runs its own instance of an operating system. Modern nodes have multiple chips, often known as Central Processing Units or CPUs, which each contain multiple cores each capable of processing a separate stream of instructions (such as a single Monte Carlo run). An example cluster configuration is shown in Figure 1.

Figure 1. An example cluster configuration

To efficiently make use of a cluster’s computational resources, it is essential to allow multiple users to use the resource at one time and to have an efficient and equatable way of allocating and scheduling computing resources on a cluster. This role is done by job scheduling software. The scheduling software is accessed via a shell script called in the command line. A scheduling  script does not actually run any code, rather it provides a set of instructions for the cluster specifying what code to run and how the cluster should run it. Instructions called from a scheduling script may include but are not limited to:

• What code would you like the cluster to run
• How would you like to parallelize your code (ie MPI, openMP ect)
• How many nodes would you like to run on
• How many core per processor would you like to run (normally you would use the maximum allowable per processor)
• Where would you like error and output files to be saved

This post will highlight two commonly used Job Scheduling Languages, PBS and SLURM and detail some simple example scripts for using them.

## PBS

The Portable Batching System (PBS) was originally developed by NASA in the early 1990’s [1] to facilitate access to computing resources.  The intellectual property associated with the software is now owned by Altair Engineering. PBS is a fully open source system and the source code can be found here. PBS is the job scheduler we use for the Cube Cluster here at Cornell.

An annotated PBS submission script called “PBSexample.sh” that runs a C++ code called “triangleSimulation.cpp” on 128 cores can be found below:

#PBS -l nodes=8:ppn=16    # how many nodes, how many cores per node (ppn)
#PBS -l walltime=5:00:00  # what is the maximum walltime for this job
#PBS -N SimpleScript      # Give the job this name.
#PBS -j oe                # combine error and output file
#PBS -o outputfolder/output.out # name output file

cd PBS_O_WORKDIR # change working directory to current folder #module load openmpi/intel # load MPI (Intel implementation) time mpirun ./triangleSimulation -m batch -r 1000 -s 1 -c 5 -b 3 To submit this PBS script via the command line one would type: qsub PBSexample.sh Other helpful PBS commands for UNIX can be found here. For more on PBS flags and options, see this detailed post from 2012 and for more example PBS submission scripts see Jon Herman’s Github repository here. ## SLURM A second common job scheduler is know as SLURM. SLURM stands for “Simple Linux Utility Resource Management” and is the scheduler used on many XSEDE resources such as Stampede2 and Comet. An example SLURM submission script named “SLURMexample.sh” that runs “triangleSimulation.cpp” on 128 core can be found below: #!/bin/bash #SBATCH --nodes=8 # specify number of nodes #SBATCH --ntasks-per-node=16 # specify number of core per node #SBATCH --export=ALL #SBATCH -t 5:00:00 # set max wallclock time #SBATCH --job-name="triangle" # name your job #SBATCH --output="outputfolder/output.out" #ibrun is the command for MPI ibrun -v ./triangleSimulation -m batch -r 1000 -s 1 -c 5 -b 3 -p 2841 To submit this SLURM script from the command line one would type: sbatch SLURM The Cornell Center for Advanced Computing has an excellent SLURM training module within the introduction to Stampede2 workshop that goes into detail on how to most effectively make use of SLURM. More examples of SLURM submission scripts can be found on Jon Herman’s Github. Billy also wrote a blog post last year about debugging with SLURM. ## References # Launching Jupyter Notebook Using an Icon/Shortcut in the Current Working Directory Folder A petty annoyance I’ve encountered when wanting to open Jupyter Notebook (overview) is that I couldn’t find a way to instantly open it in my current Windows Explorer window. While one trick you can use to open the Command Prompt in this folder is by typing ‘cmd’ in the navigation bar above (shown below) and pressing Enter/Return, I wanted to create a shortcut or icon I could double-click in any given folder and have it open Jupyter Notebook in that same working directory. This method allows you to drag-and-drop the icon you create into any folder and have it launch Jupyter Notebook from the new folder. It works for Windows 7, 8, and 10. Please feel free to let me know if you encounter any errors! A great application for this shortcut may be to include this shortcut in GitHub folders where you wish to direct someone to launch Jupyter Notebook with minimal confusion. Just direct them to double-click on the icon and away they go! # Creating Your Own Jupyter Notebook Shortcut To begin, we must have already installed Jupyter Notebook or Jupyter Lab. Next, navigate to the folder we want to create your shortcut. Right-click, select ‘New’, then create a shortcut. In the Create Shortcut Windows prompt, type the location of the item you want the Shortcut Icon to direct to. In this case, we are wanting direct this shortcut to the Command Prompt and have it run the command to open Jupyter Notebook. Copy/paste or type the following into the prompt: cmd /k “jupyter notebook” Note that cmd will change to the location of the Command Prompt executable file (e.g. C:\Windows\System32\cmd.exe), and ‘/k’ keeps the Command Prompt window open to ensure Jypyter Notebook does not crash. You can edit the command in the quotation marks to any command you would want, but in this case ‘jupyter notebook’ launches an instance of Jupyter Notebook. You can then save this shortcut with whatever name you wish! At this point, double-clicking the shortcut will open Jupyter Notebook in a static default directory (e.g. ‘C:\Windows\system32’). To fix this, we need to ensure that this shortcut instead directs to the current working directory (the location of the shortcut). Next, we need to edit the location where the Command Prompt will run in. Right-click on your newly-created icon and select ‘Properties’ at the bottom of the menu to open the window shown on the left. One thing to note is that the ‘Target’ input is where we initially put in our ‘location’ prompt from above. At this point, change the ‘Start in:’ input (e.g. ‘C:\Windows\system32’) to the following: %cd% By changing this input, instead of starting the Command Prompt in a static default directory, it instead starts the command prompt in the current working directory for the shortcut. At this point, you’re finished! You can drag and drop this icon to any new folder and have Jupyter Notebook start in that new folder. If you wish to download a copy of the shortcut from Dropbox. Note that for security reasons, most browsers, hosting services, and email services will rename the file from ‘jupyter_notebook_shortcut.lnk’ to ‘jupyter_notebook_shortcut.downloads’. Many thanks to users on superuser for helping develop this solution! Please let me know if you have any questions, comments, or additional suggestions on applications for this shortcut! # Plotting trajectories and direction fields for a system of ODEs in Python The aim of this post is to guide the reader through plotting trajectories and direction fields for a system of equations in Python. This is useful when investigating the equilibria and stability of the system, and to facilitate in understanding the general behavior of a system under study. I will use a system of predator-prey equations, that my most devoted online readers are already familiar with from my previous posts on identifying equilibria and stability, and on nondimensionalization. Specifically, I’ll be using the Lotka-Volterra set of equations with Holling’s Type II functional response: $\frac{\mathrm{d} x}{\mathrm{d} t}=bx\left ( 1-\frac{x}{K} \right )-\frac{axy}{1+ahx}$ $\frac{\mathrm{d} y}{\mathrm{d} t}=\frac{caxy}{1+ahx}-dy$ where: x: prey abundance y: predator abundance b: prey growth rate d: predator death rate c: rate with which consumed prey is converted to predator a: rate with which prey is killed by a predator per unit of time K: prey carrying capacity given the prey’s environmental conditions h: handling time This system has 3 equilibria: when both species are dead (0,0), when predators are dead and the prey grows to its carrying capacity (K,0) and a non-trivial equilibrium where both species coexist and is generally more interesting, given by: $y^*=\frac{b}{a}(1+ahx^*)\left(1-\frac{x^*}{K} \right)$ $x^*=\frac{d}{a(c-dh)}$ The following code should produce both trajectories and direction fields for this system of ODEs (python virtuosos please excuse the extensive commenting, I try to comment as much as possible for people new to python): import numpy as np from matplotlib import pyplot as plt from scipy import integrate # I'm using this style for a pretier plot, but it's not actually necessary plt.style.use('ggplot') """ This is to ignore RuntimeWarning: invalid value encountered in true_divide I know that when my populations are zero there's some division by zero and the resulting error terminates my function, which I want to avoid in this case. """ np.seterr(divide='ignore', invalid='ignore') # These are the parameter values we'll be using a = 0.005 b = 0.5 c = 0.5 d = 0.1 h = 0.1 K = 2000 # Define the system of ODEs # P[0] is prey, P[1] is predator def fish(P, t=0): return ([b*P[0]*(1-P[0]/K) - (a*P[0]*P[1])/(1+a*h*P[0]), c*(a*P[0]*P[1])/(1+a*h*P[0]) - d*P[1] ]) # Define equilibrium point EQ = ([d/(a*(c-d*h)),b*(1+a*h*(d/(a*(c-d*h))))*(1-(d/(a*(c-d*h)))/K)/a]) """ I need to define the possible values my initial points will take as they relate to the equilibrium point. In this case I chose to plot 10 trajectories ranging from 0.1 to 5 """ values = np.linspace(0.1, 5, 10) # I want each trajectory to have a different color vcolors = plt.cm.autumn_r(np.linspace(0.1, 1, len(values))) # Open figure f = plt.figure() """ I need to define a range of time over which to integrate the system of ODEs The values don't really matter in this case because our system doesn't have t on the right hand side of dx/dt and dy/dt, but it is a necessary input for integrate.odeint. """ t = np.linspace(0, 150, 1000) # Plot trajectories by looping through the possible values for v, col in zip(values, vcolors): # Starting point of each trajectory P0 = [E*v for E in EQ] # Integrate system of ODEs to get x and y values P = integrate.odeint(fish, P0, t) # Plot each trajectory plt.plot( P[:,0], P[:,1], # Different line width for different trajectories (optional) lw=0.5*v, # Different color for each trajectory color=col, # Assign starting point to trajectory label label='P0=(%.f, %.f)' % ( P0[0], P0[1]) ) """ To plot the direction fields we first need to define a grid in order to compute the direction at each point """ # Get limits of trajectory plot ymax = plt.ylim(ymin=0)[1] xmax = plt.xlim(xmin=0)[1] # Define number of points nb_points = 20 # Define x and y ranges x = np.linspace(0, xmax, nb_points) y = np.linspace(0, ymax, nb_points) # Create meshgrid X1 , Y1 = np.meshgrid(x,y) # Calculate growth rate at each grid point DX1, DY1 = fish([X1, Y1]) # Direction at each grid point is the hypotenuse of the prey direction and the # predator direction. M = (np.hypot(DX1, DY1)) # This is to avoid any divisions when normalizing M[ M == 0] = 1. # Normalize the length of each arrow (optional) DX1 /= M DY1 /= M plt.title('Trajectories and direction fields') """ This is using the quiver function to plot the field of arrows using DX1 and DY1 for direction and M for speed """ Q = plt.quiver(X1, Y1, DX1, DY1, M, pivot='mid', cmap=plt.cm.plasma) plt.xlabel('Prey abundance') plt.ylabel('Predator abundance') plt.legend(bbox_to_anchor=(1.05, 1.0)) plt.grid() plt.xlim(0, xmax) plt.ylim(0, ymax) plt.show() This should produce the following plot. All P0s are the initial conditions we defined. We can also see that this parameter combination produces limit cycles in our system. If we change the parameter values to: a = 0.005 b = 0.5 c = 0.5 d = 0.1 h = 0.1 K = 200 i.e. reduce the available resources to the prey, our trajectories look like this: The equilibrium becomes stable, attracting the trajectories to it. The same can be seen if we increase the predator death rate: a = 0.005 b = 0.5 c = 0.5 d = 1.5 h = 0.1 K = 2000 The implication of this observation is that an initially stable system, can become unstable given more resources for the prey or less efficient predators. This has been referred to as the Paradox of Enrichment and other predator-prey models have tried to address it (more on this in future posts). P.S: I would also like to link to this scipy tutorial, that I found very helpful and that contains more plotting tips. # Map making in Matlab Greetings, This weeks post will cover the basics of generating maps in Matlab. Julie’s recent post showed how to do some of this in Python, but, Matlab is also widely used by the community. You can get a lot done with Matlab, but in this post we’ll just cover a few of the basics. We’ll start off by plotting a map of the continental United States, with the states. We used three this with three commands: usamap, shaperead, and geoshow. usamap creates an empty map axes having the Lambert Projection covering the area of the US, or any state or collection of states. shaperead reads shapefiles (duh) and returns a Matlab geographic data structure, composed of both geographic data and attributes. This Matlab data structure then interfaces really well with various Matlab functions (duh). Finally, geoshow plots geographic data, in our case on the map axes we defined. Here’s some code putting it all together. hold on figure1 = figure; ax = usamap('conus'); set(ax, 'Visible', 'off') latlim = getm(ax, 'MapLatLimit'); lonlim = getm(ax, 'MapLonLimit'); states = shaperead('usastatehi',... 'UseGeoCoords', true, 'BoundingBox', [lonlim', latlim']); geoshow(ax, states, 'FaceColor', [0.5 0.5 0.5]) tightmap hold off Note that ‘usastatehi’ is a shapefile containing the US states (duh) that’s distributed with Matlab. The above code generates this figure: Now, suppose we wanted to plot some data, say a precipitation forecast, on our CONUS map. Let’s assume our forecast is being made at many points (lat,long). To interpolate between the points for plotting we’ll use Matlab’s griddata function. Once we’ve done this, we use the Matlab’s contourm command. This works exactly like the normal contour function, but the ‘m’ indicates it plots map data. xi = min(x):0.5:max(x); yi = min(y):0.5:max(y); [XI, YI] = meshgrid(xi,yi); ZI = griddata(x,y,V,XI,YI); hold on figure2 = figure; ax = usamap('conus'); set(ax, 'Visible', 'off') latlim = getm(ax, 'MapLatLimit'); lonlim = getm(ax, 'MapLonLimit'); states = shaperead('usastatehi',... 'UseGeoCoords', true, 'BoundingBox', [lonlim', latlim']); geoshow(ax, states, 'FaceColor', [0.5 0.5 0.5]) contourm(YI,-1*XI,ZI) tightmap hold off Here x, y, and V are vectors of long, lat, and foretasted precipitation respectively. This code generates the following figure: Wow! Louisiana is really getting hammered! Let’s take a closer look. We can do this by changing the entry to usamap to indicate we want to consider only Louisiana. Note, usamap accepts US postal code abbreviations. ax = usamap('LA'); Making that change results in this figure: Neat! We can also look at two states and add annotations. Suppose, for no reason in particular, you’re interested in the location of Tufts University relative to Cornell. We can make a map to look at this with the textm and scatterm functions. As before, the ‘m’ indicates the functions plot on a map axes. hold on figure4 = figure; ax = usamap({'MA','NY'}); set(ax, 'Visible', 'off') latlim = getm(ax, 'MapLatLimit'); lonlim = getm(ax, 'MapLonLimit'); states = shaperead('usastatehi',... 'UseGeoCoords', true, 'BoundingBox', [lonlim', latlim']); geoshow(ax, states, 'FaceColor', [0.5 0.5 0.5]) scatterm(42.4075,-71.1190,100,'k','filled') textm(42.4075+0.2,-71.1190+0.2,'Tufts','FontSize',30) scatterm(42.4491,-76.4842,100,'k','filled') textm(42.4491+0.2,-76.4842+0.2,'Cornell','FontSize',30) tightmap hold off This code generates the following figure. Cool! Now back to forecasts. NOAA distributes short term Quantitative Precipitation Forecasts (QPFs) for different durations every six hours. You can download these forecasts in the form of shapefiles from a NOAA server. Here’s an example of a 24-hour rainfall forecast made at 8:22 AM UTC on April 29. Wow, that’s a lot of rain! Can we plot our own version of this map using Matlab! You bet! Again we’ll use usamap, shaperead, and geoshow. The for loop, (0,1) scaling, and log transform are simply to make the color map more visually appealing for the post. There’s probably a cleaner way to do this, but this got the job done! figure5 = figure; ax = usamap('conus'); S=shaperead('94q2912','UseGeoCoords',true); set(ax, 'Visible', 'off') latlim = getm(ax, 'MapLatLimit'); lonlim = getm(ax, 'MapLonLimit'); states = shaperead('usastatehi',... 'UseGeoCoords', true, 'BoundingBox', [lonlim', latlim']); geoshow(ax, states, 'FaceColor', [0.5 0.5 0.5]) p = colormap(jet); N = max(size(S)); d = zeros(N,1); for i = 1:N d(i) = log(S(i).QPF); end y=floor(((d-min(d))/range(d))*63)+1; col = p(y,:); for i = 1:N geoshow(S(i),'FaceColor',col(i,:),'FaceAlpha',0.5)%,'SymbolSpec', faceColors) end This code generates the following figure: If you are not plotting in the US, Matlab also has a worldmap command. This works exactly the same as usamap, but now for the world (duh). Matlab is distibuted with a shapefile ‘landareas.shp’ which contains all of the land areas in the world (duh). Generating a global map is then trivial: figure6 = figure; worldmap('World') land = shaperead('landareas.shp', 'UseGeoCoords', true); geoshow(land, 'FaceColor', [0.15 0.5 0.15]) Which generates this figure. Matlab also comes with a number of other included that might be of interest. For instance, shapefiles detailing the locations of major world cities, lakes, and rivers. We can plot those with the following code: figure7 = figure; worldmap('World') land = shaperead('landareas.shp', 'UseGeoCoords', true); geoshow(land, 'FaceColor', [0.15 0.5 0.15]) lakes = shaperead('worldlakes', 'UseGeoCoords', true); geoshow(lakes, 'FaceColor', 'blue') rivers = shaperead('worldrivers', 'UseGeoCoords', true); geoshow(rivers, 'Color', 'blue') cities = shaperead('worldcities', 'UseGeoCoords', true); geoshow(cities, 'Marker', '.', 'Color', 'red') Which generates the figure: But suppose we’re interested in one country or a group of countries. worldmap works in the same usamap does. Also, you can plot continents, for instance Europe. worldmap('Europe') Those are the basics, but there are many other capabilities, including 3-D projections. I can cover this in a later post if there is interest. That’s it for now! # 9 basic skills for editing and creating vector graphics in Illustrator This post intends to provide guidance for editing and creating vector graphics using Adobe Illustrator. The goal is to learn some of the commonly used features to help you get started with your vectorized journey. Let it be a conceptual diagram, or a logos or cropping people out of your photo, these 9 features (and a fair amount googling) will help you do the job. Before we begin, it may be worthwhile to distinguish some of the main differences between a raster and a vector graphic. A raster image is comprised of a collection of squares or pixels, and vector graphics are based on mathematical formulas that define geometric forms (i.e. polygons, lines, curves, circles and rectangles), which makes them independent of resolution. The three main advantages of using vector graphics over raster images are illustrated below: 1. Scalability: Vector graphics scale infinitely without losing any image quality. Raster images guess the colors of missing pixels when sizing up, whereas vector graphics simply use the original mathematical equation to create a consistent shape every time. 2. Edibility: Vector files are not flattened, that is, the original shapes of an image exist separately on different layers; this provides flexibility on modifying different elements without impacting the entire image. 3. Reduced file size: A vector file only requires four data points to recreate a square ,whereas a raster image needs to store many small squares. # 9 key things to know when getting started with Adobe Illustrator: # 1. Starting a project You can start a new project simply by clicking File> New, and the following window will appear. You can provide a number of specifications for your document before starting, but you can also customize your document at any stage by clicking File> Document setup (shortcut Alt+Ctrl+P). # 2. Creating basic shapes ## Lines & Arrows Simply use the line segment tool ( A ) and remember to press the shift button to create perfectly straight lines. Arrows can be added by using the stroke window (Window> Stroke) and (B) will appear, there’s a variety of arrow styles that you can select from and scale (C). Finally, in the line segment tool you can provide the exact length of your line. ## Polygons Some shapes are already specified in Illustrator (e.g. rectangles , stars and circles (A), but many others such as triangles, need to be specified through the polygon tool. To draw a triangle I need to specify the number of sides =3 as shown in (B). ## Curvatures To generate curvatures, you can use the pen tool (A). Specify two points with the pen, hold the click in the second point and a handle will appear, this handle allows you to shape the curve. If you want to add more curvatures, draw another point (B) and drag the handle in the opposite direction of the curve. You can then select the color (C) and the width (D) of your wave. # 3. Matching colors If you need to match the color of an image (A) there are a couple of alternatives: i) Using the “Eyedrop” tool ( B). Select the component of the image that you want to match, then select the Eyedrop tool and click on the desired color (C). ii) Using the color picker panel. Select the image component with the desired color, then double click on the color picker (highlighted in red) and the following panel should appear. You can see the exact color code and you can copy and paste it on the image that you wish to edit. # 4. Extracting exact position and dimensions In the following example, I want the windows of my house to be perfectly aligned. First, in (A), I click on one of the windows of my house and the control panel automatically provides its x and y coordinates, as well its width and height. Since I want to align both of the windows horizontally, I investigate the Y coordinates of the first window and copy it onto the y coordinate of he second window as shown in (B). The same procedure would apply if you want to copy the dimensions from one figure to another. # 5. Free-style drawing and editing The pencil tool (A) is one of my favorite tools in Illustrator, since it corrects my shaky strokes, and allows me to paint free style. Once I added color and filled the blob that I drew, it started resembling more like a tree top (B). You can edit your figure by right clicking it. A menu will appear enabling you to rotate, reflect, shear and scale, among other options. I only wanted to tilt my tree so I specify a mild rotation (C). # 6. Cropping: Cropping in Illustrator requires clipping masks and I will show a couple of examples using Bone Bone, a fluffy celebrity cat. Once a .png image is imported into illustrator, it can be cropped using one of the following three methods: Method 1. Using the direct selection tool Method 2. Using shapes Method 3. Using the pen tool for a more detailed crop To reverse to the original image Select Object> Clipping mask> Release or Alt+Ctrl+7 # 7. Customize the art-board size If you want your image to be saved without extra white space (B), you can adapt the size of the canvas with the Art-board tool (or Shft+8) ( A). # 8. Using layers: Layers can help you organize artwork, specially when working with multiple components in an image. If the Layers panel is not already in your tools, you can access it through Window> Layers or through the F7 shortcut. A panel like the one below should appear. You can name the layers by double clicking on them, so you can give them a descriptive name. Note that you can toggle the visibility of each layer on or off. You can also lock a layer if you want to protect it from further change, like the house layer in the example below. Note that each layer is color-coded, my current working layer is coded in red, so when I select an element in that layer it will be highlighted in red. The layers can also have sub-layers to store individual shapes, like in the house layer, which is comprised of a collection of rectangles and a triangle. # 9. Saving vector and exporting raster Adobe Illustrator, naturally allows you to save images in many vector formats, But you can also export raster images such as .png, .jpeg, .bmp, etc.. To export raster images do File> Export and something like the blurry panel below should show up. You can specify the resolution and the color of the background. I usually like a transparent background since it allows you more flexibility when using your image in programs such as Power Point. There are many more features available in Illustrator, but this are the ones that I find myself using quite often. Also, you probably won’t have to generate images from scratch, there are many available resources online. You can download svg images for free which you an later customize in Illustrator. You can also complement this post by reading Jon Herman’s Scientific figures in Illustrator. # Using HDF5/zlib Compression in NetCDF4 Not too long ago, I posted an entry on writing NetCDF files in C and loading them in R. In that post, I mentioned that the latest and greatest version of NetCDF includes HDF5/zlib compression, but I didn’t say much more beyond that. In this post, I’ll explain briefly how to use this compression feature in your NetCDF4 files. Disclaimer: I’m not an expert in any sense on the details of compression algorithms. For more details on how HDF5/zlib compression is integrated into NetCDF, check out the NetCDF Documentation. Also, I’ll be assuming that the NetCDF4 library was compiled on your machine to enable HDF5/zlib compression. Details on building and installing NetCDF from source code can be found in the documentation too. I will be using code similar to what was in my previous post. The code generates three variables (x, y, z) each with 3 dimensions. I’ve increased the size of the dimensions by an order of magnitude to better accentuate the compression capabilities. // Loop control variables int i, j, k; // Define the dimension sizes for // the example data. int dim1_size = 100; int dim2_size = 50; int dim3_size = 200; // Define the number of dimensions int ndims = 3; // Allocate the 3D vectors of example data float x[dim1_size][dim2_size][dim3_size]; float y[dim1_size][dim2_size][dim3_size]; float z[dim1_size][dim2_size][dim3_size]; // Generate some example data for(i = 0; i < dim1_size; i++) { for(j = 0; j < dim2_size; j++) { for(k = 0; k < dim3_size; k++) { x[i][j][k] = (i+j+k) * 0.2; y[i][j][k] = (i+j+k) * 1.7; z[i][j][k] = (i+j+k) * 2.4; } } } Next is to setup the various IDs, create the NetCDF file, and apply the dimensions to the NetCDF file. This has not changed since the last post. // Allocate space for netCDF dimension ids int dim1id, dim2id, dim3id; // Allocate space for the netcdf file id int ncid; // Allocate space for the data variable ids int xid, yid, zid; // Setup the netcdf file int retval; if((retval = nc_create(ncfile, NC_NETCDF4, &ncid))) { ncError(retval); } // Define the dimensions in the netcdf file if((retval = nc_def_dim(ncid, "dim1_size", dim1_size, &dim1id))) { ncError(retval); } if((retval = nc_def_dim(ncid, "dim2_size", dim2_size, &dim2id))) { ncError(retval); } if((retval = nc_def_dim(ncid, "dim3_size", dim3_size, &dim3id))) { ncError(retval); } // Gather the dimids into an array for defining variables in the netcdf file int dimids[ndims]; dimids[0] = dim1id; dimids[1] = dim2id; dimids[2] = dim3id; Here’s where the magic happens. The next step is to define the variables in the NetCDF file. The variables must be defined in the file before you tag it for compression. // Define the netcdf variables if((retval = nc_def_var(ncid, "x", NC_FLOAT, ndims, dimids, &xid))) { ncError(retval); } if((retval = nc_def_var(ncid, "y", NC_FLOAT, ndims, dimids, &yid))) { ncError(retval); } if((retval = nc_def_var(ncid, "z", NC_FLOAT, ndims, dimids, &zid))) { ncError(retval); } Now that we’ve defined the variables in the NetCDF file, let’s tag them for compression. // OPTIONAL: Compress the variables int shuffle = 1; int deflate = 1; int deflate_level = 4; if((retval = nc_def_var_deflate(ncid, xid, shuffle, deflate, deflate_level))) { ncError(retval); } if((retval = nc_def_var_deflate(ncid, yid, shuffle, deflate, deflate_level))) { ncError(retval); } if((retval = nc_def_var_deflate(ncid, zid, shuffle, deflate, deflate_level))) { ncError(retval); } The function nc_def_var_deflate() performs this. It takes the following parameters: • int ncid – The NetCDF file ID returned from the nc_create() function • int varid – The variable ID associated with the variable you would like to compress. This is returned from the nc_def_var() function • int shuffle – Enables the shuffle filter before compression. Any non-zero integer enables the filter. Zero disables the filter. The shuffle filter rearranges the byte order in the data stream to enable more efficient compression. See this performance evaluation from the HDF group on integrating a shuffle filter into the HDF5 algorithm. • int deflate – Enable compression at the compression level indicated in the deflate_level parameter. Any non-zero integer enables compression. • int deflate_level – The level to which the data should be compressed. Levels are integers in the range [0-9]. Zero results in no compression whereas nine results in maximum compression. The rest of the code doesn’t change from the previous post. // OPTIONAL: Give these variables units if((retval = nc_put_att_text(ncid, xid, "units", 2, "cm"))) { ncError(retval); } if((retval = nc_put_att_text(ncid, yid, "units", 4, "degC"))) { ncError(retval); } if((retval = nc_put_att_text(ncid, zid, "units", 1, "s"))) { ncError(retval); } // End "Metadata" mode if((retval = nc_enddef(ncid))) { ncError(retval); } // Write the data to the file if((retval = nc_put_var(ncid, xid, &x[0][0][0]))) { ncError(retval); } if((retval = nc_put_var(ncid, yid, &y[0][0][0]))) { ncError(retval); } if((retval = nc_put_var(ncid, zid, &z[0][0][0]))) { ncError(retval); } // Close the netcdf file if((retval = nc_close(ncid))) { ncError(retval); } So the question now is whether or not it’s worth compressing your data. I performed a simple experiment with the code presented here and the resulting NetCDF files: 1. Generate the example NetCDF file from the code above using each of the available compression levels. 2. Time how long the code takes to generate the file. 3. Note the final file size of the NetCDF. 4. Time how long it takes to load and extract data from the compressed NetCDF file. Below is a figure illustrating the results of the experiment (points 1-3). Before I say anything about these results, note that individual results may vary. I used a highly stylized data set to produce the NetCDF file which likely benefits greatly from the shuffle filtering and compression. These results show a compression of 97% – 99% of the original file size. While the run time did increase, it barely made a difference until hitting the highest compression levels (8,9). As for point 4, there was only a small difference in load/read times (0.2 seconds) between the uncompressed and any of the compressed files (using ncdump and the ncdf4 package in R). There’s no noticeable difference among the load/read times for any of the compressed NetCDF files. Again, this could be a result of the highly stylized data set used as an example in this post. For something more practical, I can only offer anecdotal evidence about the compression performance. I recently included compression in my current project due to the large possible number of multiobjective solutions and states-of-the-world (SOW). The uncompressed file my code produced was on the order of 17.5 GB (for 300 time steps, 1000 SOW, and about 3000 solutions). I enabled compression of all variables (11 variables – 5 with three dimensions and 6 with two dimensions – compression level 4). The next run produced just over 7000 solutions, but the compressed file size was 9.3 GB. The down side is that it took nearly 45 minutes to produce the compressed file, as opposed to 10 minutes with the previous run. There are many things that can factor into these differences that I did not control for, but the results are promising…if you’ve got the computer time. I hope you found this post useful in some fashion. I’ve been told that compression performance can be increased if you also “chunk” your data properly. I’m not too familiar with chunking data for writing in NetCDF files…perhaps someone more clever than I can write about this? Acknowledgement: I would like to acknowledge Jared Oyler for his insight and helpful advice on some of the more intricate aspects of the NetCDF library. # Useful Linux commands to handle text files and speed up work Most of us, nice and normal human beings, tend to prefer programs with GUIs over typing commands on a command prompt because the former looks more “real” and is more visual than the latter. However, one thing we don’t know (or, sometimes, don’t want to know) is that learning a few terminal commands can dramatically increase productivity. These commands can save us a lot of time by sparing us from opening and closing programs, navigating through menus and windows, moving the mouse around, as well as moving the hand back and forth from the mouse to the keyboard. This post will mention and briefly describe some useful “intermediate level” Linux commands (some basic commands are presented in this post by Jon Herman), which can be called from a Linux OS, Cygwin (mostly), or Mac. Among the numerous tedious tasks these commands can greatly simplify is the particularly interesting chore of handling text files, be they scripts or data files. Commands for other tasks are covered as well. Keep in mind that the symbol * is a wild card (character that can mean any string of characters when searching for files), which is really useful when the goal is to repeatedly apply one command to multiple files. For all commands listed here skip the “” character.

DELIMITER SEPARATED FILES HANDLING

• Remove columns 30 to 36 (starting from 0) from a comma separated file and export the output to another file.
$cut -d',' -f1-30,36 input.file >> output.file (More information on the post by Joe Kasprzyk) • Print only columns 2 and 4 (starting from 1) of a comma separated file.$ awk -F "," '{print $2,$4}' input.file >> output.file
• Count number of columns in a file separated either by spaces or commas:
$head -1 input.file | sed 's/[^, ]//g' | wc -c or:$ awk -F "[, ]" 'END{print NF}' input.file
• Print lines of a comma separated file in which the value in the 2nd column is lower than 100 and the value in the 5th column is higher than 0.3:
$awk -F "," '$2<100 && $5>0.3' input.file >> output.file • Print lines between 10th and 20th lines (not inclusive) of a file:$ awk 'NR>10 && NR<20' input.file >> output.file
• Add a string to the end of multiple files:
$echo "your string" | tee -a *.set • Add a string to the end of one file:$ echo "your string" >> file

FILE SEARCHING

• Find all text files in a folder that contain a certain string:
$grep -rn './folder' -e your_string • Find files recursively (* is a wildcard):$ find -type f -name name_of*.file

FILES INFO

• See the contents of a zip/tar file without extracting it. Press q to quit.
$less file.tar • Count number of lines in a file:$ wc -l your.file
• List all files with a certain extension in a directory:
$ls *.ext • Print files and folders in tree fashion:$ tree
• Print the size of all subfolders and files in (sub)folders to a certain max depth in the folder hierarchy:
$du -h -a --max-depth=2 IMAGE HANDLING • Convert svg files to png (you need to have Inkscape installed):$ inkscape input.svg -d 300 -e output.png
• Convert svg files to pdf-latex (you need to have Inkscape installed):
$inkscape input.svg --export-pdf output.pdf --export-latex • Rotate a picture:$ convert Fig6_prim.png -rotate 90 Fig6_prim_rotated.png

MISCELLANEOUS

• See the history of commands you have typed:
$history • See a calendar (month and year optional):$ cal [month] [year]
• Combine pdf files into one (you need to have pdftk installed):
$pdftk file1.pdf file2.pdf file3.pdf cat output newfile.pdf or, to merge all pdf files in a directory:$ pdftk *.pdf cat output newfile.pdf

In order to see how to combine only certain pagers of pdf files, as well as how to splits all pages into separate pdf files, see this page.

• See the manual of a command:
$man command Another useful idea is that of piping outputs of a command to another command. For example, if you want print the number of files in a directory, you can pipe the output of the ls command (list all files in a directory) to the wc -l command (count the number of lines in a string). For this, use the “|” character:$ ls | wc -l

However, you may want instead to check the number of lines in all the 20 files in a directory at once, which can also be achieved by combining the ls and wc commands with the command xargs. The command then would look like:

\$ ls | xargs wc -l

The command xargs breaks down the output from ls into one string per line and then calls wc -l for each line of the output of ls.

Hope all this saves you some time!