Skip to content

Instantly share code, notes, and snippets.

@jdherman
Created November 18, 2014 20:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jdherman/fe0b81100ee83e1f6532 to your computer and use it in GitHub Desktop.
Save jdherman/fe0b81100ee83e1f6532 to your computer and use it in GitHub Desktop.
SALib parameter samples into input file template
from SALib.sample import saltelli
from string import Template
# Generate samples for sensitivity analysis, and put them into an input file template
# This will generate N(2D+2) copies of the template with the values inserted
# The use case is for older models (like F77) where the input file something like below.
# Put dollar-sign variables where you want to replace with numbers, like so:
#
#C IWQVLIM = option for velocity limitation of macroalgae growth
#C = 0, macroalgae growth is not limited by stream velocity
#C = 1, macroalgae growth limited using Michaelis-Menton formula
#C = 2, macroalgae growth limited using 5-parameter Logistic Function
#C
#C03 IWQDT IWQM IWQBEN IWQSI IWQFCB IWQSRP IWQSTOX IWQKA IWQVLIM IWQOSS
# 1 1 1 $IWQSI 0 2 $IWQSTOX 1 0 1
#C-----------------------------------------------------------------------------
# parameter file: 3 columns: name, lower bound, upper bound
param_file = './parameter-ranges.txt'
# Generate samples from SALib
param_values = saltelli.sample(1000, param_file, calc_second_order=True)
N = param_values.shape[0]
D = param_values.shape[1]
param_names = ['SLP','KRN','KLN','KDN','KRP','KLP','KDP','KRC','KLC','KN']
# These names must appear in the template file as $SLP, $KRN, etc.
with open('./my-template-file.txt', 'r') as T:
template = Template(T.read())
d = {}
for i in range(N):
for j in range(D):
d[param_names[j]] = '%.3f' % param_values[i,j]
# substitute the dollar-sign variables with floating point values (converted to 3 decimal place string)
s1 = template.safe_substitute(d)
with open('./output-file-' + str(i) + '.txt', 'w') as f1:
f1.write(s1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment