Skip to content
This repository was archived by the owner on Aug 22, 2019. It is now read-only.

Commit 7335bca

Browse files
committed
updated with FDSa syntax...
need to now update readme, and get rid of dict_builder function / tests.
1 parent 65956e0 commit 7335bca

5 files changed

+165
-60
lines changed

example_input_file.fds

+3-3
Original file line numberDiff line numberDiff line change
@@ -7,12 +7,12 @@
77
&MISC DNS=.TRUE., RADIATION=.TRUE. /
88

99
&SURF ID = 'HOT',
10-
TMP_FRONT = {WALL_TEMP},
10+
TMP_FRONT = {WALL_TEMP SWEEP 200, 400, 4},
1111
TAU_T = 0.1,
1212
EMISSIVITY = 0.8/
1313

1414
&SURF ID = 'COLD',
15-
TMP_FRONT = {COLD_TEMP},
15+
TMP_FRONT = {COLD_TEMP SWEEP 20, 20, 1},
1616
TAU_T = 0.1,
1717
EMISSIVITY = 0.8/
1818

@@ -21,7 +21,7 @@
2121
&VENT MB='ZMAX', SURF_ID='COLD' /
2222

2323
&OBST XB= -0.45, 0, -0.3, 0.3, 0.0, 0.1, SURF_ID6(2)='HOT' /
24-
&OBST XB= {STEP_WMAX}, 0.55, -0.3, 0.3, 0.0, 0.1 /
24+
&OBST XB= {STEP_WMAX SWEEP 0.1, 0.3, 4}, 0.55, -0.3, 0.3, 0.0, 0.1 /
2525

2626
&BNDF QUANTITY='WALL TEMPERATURE' /
2727

helper_functions.py

+141-40
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import os, itertools, shutil, re, string
1+
import os, itertools, shutil, re, string, sys
22
import numpy as np
33

44
def dict_product(dicts):
@@ -11,9 +11,9 @@ def dict_product(dicts):
1111
eg: from: {'a': [0,1], 'b': [2,3], 'c': [4]}
1212
1313
outputs: [{'a': 0, 'b': 2, 'c': 4},
14-
{'a': 0, 'b': 3, 'c': 4},
15-
{'a': 1, 'b': 2, 'c': 4},
16-
{'a': 1, 'b': 3, 'c': 4}]
14+
{'a': 0, 'b': 3, 'c': 4},
15+
{'a': 1, 'b': 2, 'c': 4},
16+
{'a': 1, 'b': 3, 'c': 4}]
1717
"""
1818
# from http://stackoverflow.com/questions/5228158/cartesian-product-of-a-dictionary-of-lists
1919
return (dict(itertools.izip(dicts, x)) for x in itertools.product(*dicts.itervalues()))
@@ -61,31 +61,46 @@ def input_directory_builder(folder_name, base_path):
6161
finally:
6262
os.chdir(calling_dir)
6363

64-
def build_input_files(base_file, params, base_path = 'input_files', test_name = ''):
65-
"""
66-
build_input_files(base_file, params, base_path = 'input_files')
67-
68-
takes a 'well-formated' input file, a set of parameters in a dict,
69-
and outputs a directory structure with the properly formated input files
70-
created in them.
71-
"""
72-
calling_dir = os.getcwd()
73-
74-
with open(base_file, 'r') as f:
75-
txt = f.read()
76-
77-
for value_set in dict_builder(params, test_name = test_name):
78-
tmp_txt = txt
79-
# make a directory
80-
input_directory_builder(value_set['TITLE'], base_path)
81-
# populate the input file
82-
tmp_txt = tmp_txt.format(**value_set)
83-
# create the file name
84-
fname = os.path.join(calling_dir, base_path,
85-
value_set['TITLE'], value_set['TITLE']+'.fds')
86-
# write the input file to the directory
87-
with open(fname, 'w') as f:
88-
f.write(str(tmp_txt))
64+
def build_input_files(filename, base_path = 'input_files', out = sys.stdout):
65+
"""
66+
build_input_files(filename, base_path = 'input_files')
67+
68+
takes a 'well-formated' input fileand outputs a
69+
directory structure with the properly formated input files
70+
created in them.
71+
"""
72+
calling_dir = os.getcwd()
73+
74+
# I'm doing this because I need it later
75+
file_path, file_name = os.path.split(filename)
76+
77+
with open(filename, 'r') as f:
78+
txt = f.read()
79+
80+
formatted_trials, logfile, out = FDSa_parser(filename, base_path, out)
81+
82+
for i, value_set in enumerate(formatted_trials):
83+
tmp_txt = txt
84+
# make a directory
85+
case_name = 'case_'+int2base(i, 26)
86+
# FDS uses uppercase reseved keywords, and so will we
87+
value_set['TITLE'] = case_name
88+
input_directory_builder(case_name, base_path)
89+
# populate the input file
90+
tmp_txt = tmp_txt.format(**value_set)
91+
# create the file name
92+
fname = os.path.join(calling_dir, base_path,
93+
case_name, case_name + '.fds')
94+
# write the input file to the directory
95+
with open(fname, 'w') as f:
96+
f.write(str(tmp_txt))
97+
98+
log_path_name = os.path.join(calling_dir, base_path, file_name[:-4] + '.log')
99+
100+
with open(log_path_name, 'a') as f:
101+
f.write(logfile)
102+
103+
return out
89104

90105
def input_file_paths(base_path):
91106
"""
@@ -96,18 +111,17 @@ def input_file_paths(base_path):
96111
"""
97112
paths = []
98113
for dirpath, dirnames, filenames in os.walk(base_path):
99-
for onefile in filenames:
100-
# the following if statement is due to OS X .DsStore bullshit...
101-
if not onefile.startswith('.DS'):
102-
#paths.append(dirpath+"/"+onefile)
103-
paths.append(os.path.join(os.getcwd(), dirpath, onefile))
114+
for onefile in filenames:
115+
# the following if statement is due to OS X .DsStore bullshit...
116+
if not onefile.startswith('.DS'):
117+
#paths.append(dirpath+"/"+onefile)
118+
paths.append(os.path.join(os.getcwd(), dirpath, onefile))
104119
return paths
105-
106-
def int2base(x, base):
120+
121+
def int2base(x, base=26):
107122
"""
108-
int2base(x, base) takes an integer and returns the base representation in
109-
alphabetical order like one would see in excel column labeling
110-
(0 -> a, 27 -> ab in base 26)
123+
int2base(x, base) takes an integer and returns the base 26 representation (defualt) in letters
124+
like one would see in excel column labeling (0 -> a, 63 -> cl)
111125
112126
based on https://stackoverflow.com/questions/2267362
113127
"""
@@ -130,4 +144,91 @@ def int2base(x, base):
130144
digits.append('-')
131145
digits.reverse()
132146
#
133-
return ''.join(digits)[::-1]
147+
return ''.join(digits)[::-1]
148+
149+
def FDSa_parser(filename, base_path, out=sys.stdout):
150+
"""
151+
FDSa_parser(filename, base_path, out) takes in an augmented FDS file and determines how many parametric will be created from that
152+
it also parses the augmented syntax to build the dictionary used in generating the specific case FDS files
153+
"""
154+
# I'm doing this because I need it later
155+
file_path, file_name = os.path.split(filename)
156+
# open the augmented fds input file
157+
with open(os.path.join(file_path, file_name), 'r') as f:
158+
read_data = f.read()
159+
160+
regex_find = re.findall('\{*[0-9a-zA-Z_:,.\s]*\}', read_data)
161+
162+
params = []
163+
params_raw = []
164+
165+
for param in regex_find:
166+
params_raw.append(param.strip('{}'))
167+
params.append(param.strip('{}').split('SWEEP'))
168+
169+
params = [item.strip() for sublist in params for item in sublist]
170+
171+
# if length of params is non-even that means I can assume a title parameter
172+
# double check with the occurance of FDSa 'reserved' keywords 'title' or 'name'
173+
if (len(params) % 2 != 0) and (params[0].lower() == ('title')):
174+
# based on the following idiom
175+
# https://stackoverflow.com/questions/3303213
176+
param_dict = dict(zip(params[1::2], params[2::2]))
177+
param_list = [params[0]]
178+
param_list.extend(params[1::2])
179+
params_name_dict = dict(zip(param_list, params_raw))
180+
else:
181+
param_dict = dict(zip(params[::2], params[1::2]))
182+
param_list = params[::2]
183+
params_name_dict = dict(zip(param_list, params_raw))
184+
185+
186+
out.write('-'*10 + 'ParFDS input file interpreter' + '-'*10 + '\n')
187+
out.write('the following are the keys and values'+ '\n')
188+
out.write('seen in ' + filename + '\n')
189+
190+
permutations = 1
191+
for key, value in param_dict.iteritems():
192+
value_str = 'np.linspace(' + value.replace("'", "") +')'
193+
param_dict[key] = eval(value_str, {"__builtins__":None},
194+
{"np": np,"np.linspace":np.linspace,"np.logspace":np.logspace})
195+
value_split = value.split(',')
196+
197+
assert float(value_split[2]) >= 1, "the number of steps is not an integer: %r" % float(value_split[2].strip())
198+
199+
permutations *= int(value_split[2])
200+
201+
out.write(key + ' varied between ' + str(value_split[0]) +\
202+
' and ' + str(value_split[1]) + ' in ' + str(value_split[2]) + ' step(s)' + '\n')
203+
204+
out.write('-'*10 + ' '*10 + '-'*10 + ' '*10 + '-'*10 + '\n')
205+
out.write('for a total of ' + str(permutations) + ' trials' + '\n')
206+
207+
trials = dict_product(param_dict)
208+
209+
logfile = 'There are a total of ' + str(permutations) + ' trials \n'
210+
newline = '\n' # for the newlines
211+
formatted_trials = []
212+
213+
base = 26
214+
for i, v in enumerate(trials):
215+
case_temp = 'case ' + int2base(i, base) + ': '
216+
logfile += case_temp
217+
out.write(case_temp,)
218+
for key, val in v.iteritems():
219+
kv_temp = key + ' ' + str(round(val, 2)) + ' '
220+
logfile += kv_temp + ' '
221+
out.write(kv_temp,)
222+
out.write(newline)
223+
logfile += newline
224+
formatted_trials.append({params_name_dict[key] : round(value, 3) for key, value in v.items() })
225+
# write the augmented fds log file
226+
227+
"""
228+
>>> important_dict = {'x':1, 'y':2, 'z':3}
229+
>>> name_replacer = {'x':'a', 'y':'b', 'z':'c'}
230+
>>> {name_replacer[key] : value for key, value in important_dict.items() }
231+
{'a': 1, 'b': 2, 'c': 3}
232+
"""
233+
# out.getvalue().strip()
234+
return formatted_trials, logfile, out

parFDS.py

+3-7
Original file line numberDiff line numberDiff line change
@@ -51,10 +51,9 @@ def fds_calculation(input_path):
5151
os.chdir(cur_dir)
5252
return retcode
5353

54-
def main(input_file, parameters, **kwargs):
55-
build_input_files(input_file, parameters,
56-
base_path = kwargs['base_path'],
57-
test_name = kwargs['test_name'])
54+
def main(input_file, **kwargs):
55+
build_input_files(input_file,
56+
base_path = kwargs['base_path'])
5857
paths = input_file_paths(kwargs['base_path'])
5958
pool = build_pool(multiproc = kwargs['multiproc'],
6059
pool_size = kwargs['pool_size'])
@@ -92,9 +91,6 @@ def plotter(parameters, plotted_val = 'HRR', **kwargs):
9291

9392
if __name__ == '__main__':
9493
input_file = 'example_input_file.fds'
95-
parameters = {'STEP_WMAX': np.linspace(0.05,0.4,4),
96-
'WALL_TEMP': np.ceil(np.linspace(50, 200, 4)),
97-
'COLD_TEMP': [25.0]}
9894
kwargs = {'test_name' : 'StepBoxDan',
9995
'base_path' : 'input_files',
10096
'funct' : fds_calculation,

tests/input_file_builder.fds

+4-1
Original file line numberDiff line numberDiff line change
@@ -1 +1,4 @@
1-
{TITLE} {a} {b} {c}
1+
&CHID = '{TITLE}' /
2+
A = {A SWEEP 0, 1, 3} /
3+
B = {B SWEEP 2, 3, 2} /
4+
C = {C SWEEP 4, 4, 1} /

tests/test_input_file_builder.py

+14-9
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import nose, os, shutil, multiprocessing
1+
import nose, os, shutil, multiprocessing, StringIO
22
from sets import Set
33

44
from nose.tools import with_setup
@@ -9,25 +9,30 @@
99
#### tests ####
1010
class Test_build_input_files(object):
1111
def __init__(self):
12-
self.x = {'a': [0,1], 'b': [2,3], 'c': [4]}
13-
self.test_name = 'STEP_BOX'
1412
self.base_path = 'input_files'
1513
self.file_name = './tests/input_file_builder.fds'
1614

1715
def setup(self):
18-
build_input_files(self.file_name, self.x,
19-
base_path = self.base_path, test_name = self.test_name)
16+
self.out = StringIO.StringIO()
17+
self.output = build_input_files(self.file_name, base_path = self.base_path, out = self.out)
18+
self.output = self.output.getvalue().strip()
19+
20+
# build_input_files(self.file_name, base_path = self.base_path)
2021

2122
def teardown(self):
2223
shutil.rmtree(self.base_path)
2324

2425
def build_input_files_test(self):
2526
file_list = Set(input_file_paths(self.base_path))
26-
vals = Set([os.path.join(os.getcwd(),'input_files/STEP_BOX0-4-2/STEP_BOX0-4-2.fds'),
27-
os.path.join(os.getcwd(),'input_files/STEP_BOX0-4-3/STEP_BOX0-4-3.fds'),
28-
os.path.join(os.getcwd(),'input_files/STEP_BOX1-4-2/STEP_BOX1-4-2.fds'),
29-
os.path.join(os.getcwd(),'input_files/STEP_BOX1-4-3/STEP_BOX1-4-3.fds')])
27+
vals = Set([os.path.join(os.getcwd(),'input_files/input_file_builder.log'),
28+
os.path.join(os.getcwd(),'input_files/case_a/case_a.fds'),
29+
os.path.join(os.getcwd(),'input_files/case_b/case_b.fds'),
30+
os.path.join(os.getcwd(),'input_files/case_c/case_c.fds'),
31+
os.path.join(os.getcwd(),'input_files/case_d/case_d.fds'),
32+
os.path.join(os.getcwd(),'input_files/case_e/case_e.fds'),
33+
os.path.join(os.getcwd(),'input_files/case_f/case_f.fds')])
3034
assert Set(file_list) == Set(vals)
35+
print self.output
3136

3237
class Test_build_pool_1(object):
3338
def __init__(self):

0 commit comments

Comments
 (0)